Wednesday, May 13, 2020

react hooks, updating 'initial state' for repeated renders of a modal

Hooks really feel like the right thing for React and for small to medium-sized components they make it easy to bundle all your state right there in what is otherwise a pure functional component

The paradigm for tying in an input field to the state is pretty clean-

First you get the local variable and a way of changing it:
const [name, setName] = useState('');
Then you render an input field like this:
<input value={name} onChange={(e) => setName(e.target.value)} />

I ran into a gotcha with a react-modal component, one that is effectively reused across the life of the parent component. Using something like
const [name, setName] = useState(props.name);
wouldn't reset things so to speak - name was being reset to the initial value from the first render even as the props were updated and the entire component was being re-rendered.

The solution is to combine it with the useEffect hook to get that side effect action going:
Once you've called useState, do something like
useEffect(() => {
   setName(props.name ? props.name : '');
}, [props]);

That let the inputs have the right initial value while still updating the local state as the user typed.

No comments:

Post a Comment