re: What's hard about React Hooks for you? VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Interesting. Could you clarify what you mean?
 

When I use useState for a form field I need to update more states to track value, error, overall form. Instead of updating one json object. Idk now that I think about it, maybe it's the same thing. I like hooks more and more but I'm still in transition

This is an excellent use case for useReducer, instead of useState. With that you also make it clearer what state you’re handling, and the actions that can be used to update that state.

I don't know if useReducer would help all that much TBH, but...

You know, the setState() function returned from useState() can be passed a function, to update the state, which receives the current state and you are expected to return the new state.

setState( state => ({ ...state, updateValue: true }) );

This can be great when dealing with forms.

const [formState, setFormState] = useState({
    name: '',
    age: null,
    level: 1
});

const handleChange = ({ target: { name, value } }) => {
    return setFormState( state => ({ ...state, [name]: value }) );
}

return (
    <form>
        <input name="name" onChange={handleChange} />
        <input name="age" onChange={handleChange} type="number" />
        <select name="level" onChange={handleChange}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
    </form>
  );

Here's that code a little expanded:

I feel useReducer() doesn't add all that much to state hooks, other than being familiar to redux users. I share some of the reasons for this point of view in this talk if you are interested:
youtube.com/watch?v=gRXgE2iHRek

code of conduct - report abuse