I have a question, why did you use the useReducer instead of create a useState like const [registerForm, setRegisterForm] = useState({...})?
Great question. You could create the form like you said:
const [registerForm, setRegisterForm] = useState({ username: '', password: '', ... })
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}))
and to update the password,
(e) => setRegisterForm((prevState) => ({ ...prevState, password: e.target.value}))
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) => ({ ...prevState,
useReducer
(prevState, newState) => ({ ...prevState, ...newState })
and just pass the new state to setRegisterForm.
setRegisterForm
ohhhh make sense, thanks for the reply !
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
I have a question, why did you use the useReducer instead of create a useState like const [registerForm, setRegisterForm] = useState({...})?
Great question. You could create the form like you said:
but now the code to update the form needs to change. For example, to update the username, you'd have to write
and to update the password,
etc. You have to repeat the
(prevState) => ({ ...prevState,
part every time, which I'd rather not do. UsinguseReducer
allows me to define the update function once withand just pass the new state to
setRegisterForm
.ohhhh make sense, thanks for the reply !