DEV Community

Discussion on: Improving Your React Code - Custom Hooks

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 !