re: A React hook to handle state with dependencies VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Hi Guico33, thanks for your input. I considered your suggested approach while writing the article, but storing the selected index in state does not...
 

There's a reason whileuseMemo shouldn't be used, it runs while rendering, thus updating the state in it might not trigger a rerender and result in a stale UI.
I agree using the index may not be a safe choice, a better solution would be to use an id of some sort.
If the corresponding item is no longer there, you can reset the state to the id of the first item for instance, in a useEffect hook.
Only gotcha is if you want to keep track of an item which is no longer present in the data passed as props. Assuming the data is a list of options fetched remotely, it's unlikely you want the user to select an item which is no longer in the list returned by the server.

Even with an id, you still have the issue that, for that render, the id state value is no longer valid. This means you have to deal with checking the validity of the id twice, both in the effect, and in the render method, and the resulting code is pretty ugly and unintuitive, IMO:

const options = useMemo(() => { ... }, [apiData]);

const [selectedId, setSelectedId] = useState(options[0].id);

useEffect(() => {
  if (!isValidId(options, selectedId) {
    setSelectedId(options[0].id);
  }
}, [options]);

let selectedOption;

if (!isValidId(options, selectedId) {
  selectedOption = getById(options, selectedId);
}
else {
  selectedOption = options[0];
}

In this case, the fact that useMemo runs immediately is to our benefit, because we do want to update the state value immediately, because otherwise we're going to render invalid data. By both calling the state setter and reassigning the current state value, we avoid any problems with either invalid or stale renders. And wrapping this logic up inside a custom hook ensures that the mutability of the state variable is never leaked to the outside code.

I agree this isn't a 100% ideal solution, but I have used it and it works, without any issues regarding stale UI. However, it would be nicer if useState supported these kind of dependencies directly, which is why I raised the feature request I mentioned with the React team.

The code does not need to be so verbose, it boils down to:

const options = useMemo(() => { /*...*/ }, [apiData]);

const [selectedId, setSelectedId] = useState(options[0].id);

const selectedOption = options.find(({ id }) => selectedId === id);

useEffect(() => {
  if (!selectedOption) {
    setSelectedId(options[0].id);
  }
}, [options]);

selectedOption may not be defined so you need to account for that in your render method, but that's about the same as every time you're fetching data in a react component.
The computation of the options is a good use case for useMemo.
selectedOption could use it as well, though for both it remains an optimisation and wouldn't make a difference in most cases.

This code will render with selectedOption as null for the render before the one scheduled by the effect. What if you can't do this? You will need to add something like:

const actuallySelectedOption = selectedOption || options[0];`

In my previous comment:
selectedOption may not be defined so you need to account for that in your render method.
Defaulting it to the first option works as well. One could argue that the source of truth should be the id in state so you might wanna wait until the state has been updated and until then render something else (likely all this will be too fast to be noticeable by the user), though in the end I guess it's about the same.

code of conduct - report abuse