I'm trying to learn how React hooks work with a simple authentication modal that I've set up. I have a custom useForm
hook that handles form state, and I'm curious as to how I have access to values
before it's declared.
function LoginModal () {
console.log('outside values', values) // undefined
const submitForm = async () => {
console.log('inside values', values) // email, password values exist
const request = {
method: 'POST',
url: '/auth/login',
data: {
email: values.email,
password: values.password
}
}
await axios(request)
}
const [values, handleChange, handleSubmit] = useForm(submitForm)
return <div>some form stuff</div>
}
`useForm.js`
import { useState } from 'react'
const useForm = submitForm => {
const [state, setState] = useState({})
const handleChange = event => {
event.persist()
setState(state => ({ ...state, [event.target.name]: event.target.value }))
}
const handleSubmit = event => {
event.preventDefault()
submitForm()
}
return [state, handleChange, handleSubmit]
}
export default useForm
Can someone explain to me why values
exist only within the submitForm
function, and how it's available before const [values]
is even declared? I believe const
declarations aren't hoisted. Thanks!