Form Validation with React Hooks — useState and useEffect
Since Hooks came to React we’re all working learning new little tricks and nuances of writing function components.
Along the way, we sometime just want to “do what we did before” with classes…
I came across a neat little pattern recently using the useEffect()
hook to wrap a validation function and then only run it every time the state changes.
useEffect to wrap and call our validation function
For every change in state we want to run our validation function.
We can simply create field value variables with useState()
.
Then, we pass those state variables in to useEffect
as an array, skipping any other changes!
const [name, setName] = useState('')
const [email, setEmail] = useState('')useEffect(() => {
*** Run our validation function ***}, [name, email]) // Only re-run the effect if name or email change
Don’t run useEffect on first render — useRef( ) to the rescue
If we’re setting an initial state variable disabled
to true
with useState()
, then we don’t want to run our validation on first render.