DEV Community

Discussion on: A React hook to handle state with dependencies

 
guico33 profile image
guico33 • Edited

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.

Thread Thread
 
jonrimmer profile image
Jon Rimmer • Edited

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];`
Thread Thread
 
guico33 profile image
guico33 • Edited

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.