DEV Community

Cover image for Improving Your React Code - Custom Hooks

Improving Your React Code - Custom Hooks

Zach Taylor on February 13, 2021

One of the main reasons I, and many others, love React is that it allows us to organize markup into reusable pieces. Custom React hooks allow us t...
Collapse
 
monfernape profile image
Usman Khalil

Thank you. Requires a second read but totally worth it

Collapse
 
zachtylr21 profile image
Zach Taylor

Glad you liked it!

Collapse
 
haakonhr profile image
Haakon Helmen Rusås

Thank for this article! I've been working on a form component for some time and have been blindly adding complexity. And now that I'm trying to test and add more functionality it breaks down. Back to the basics, make it simple!

Collapse
 
kda profile image
Avishka Kapuruge

helpful

Collapse
 
pietrobelluno profile image
Pietro Belluno

I have a question, why did you use the useReducer instead of create a useState like const [registerForm, setRegisterForm] = useState({...})?

Collapse
 
zachtylr21 profile image
Zach Taylor

Great question. You could create the form like you said:

const [registerForm, setRegisterForm] = useState({
  username: '',
  password: '',
  ...
})
Enter fullscreen mode Exit fullscreen mode

but now the code to update the form needs to change. For example, to update the username, you'd have to write

(e) => setRegisterForm((prevState) => ({ ...prevState, username: e.target.value}))
Enter fullscreen mode Exit fullscreen mode

and to update the password,

(e) => setRegisterForm((prevState) => ({ ...prevState, password: e.target.value}))
Enter fullscreen mode Exit fullscreen mode

etc. You have to repeat the (prevState) => ({ ...prevState, part every time, which I'd rather not do. Using useReducer allows me to define the update function once with

(prevState, newState) => ({ ...prevState, ...newState })
Enter fullscreen mode Exit fullscreen mode

and just pass the new state to setRegisterForm.

Collapse
 
pietrobelluno profile image
Pietro Belluno

ohhhh make sense, thanks for the reply !

Collapse
 
zeque98 profile image
Zequee98 • Edited

Great article!

Collapse
 
khalilmissaoui profile image
khalilmissaoui

good job man <3

Collapse
 
vasco3 profile image
JC

which lib do you use to generate PDFs?

Collapse
 
zachtylr21 profile image
Zach Taylor

The example was meant to be hypothetical, but I've heard jspdf is a good library.