DEV Community

Cover image for useDependentState - React useState hook with dependencies
Brian Ingles
Brian Ingles

Posted on • Originally published at emeraldwalk.com

useDependentState - React useState hook with dependencies

I've been using React hooks for a bit and have found several cases where I've needed useState to update when the initial value changes. The typical pattern I've used is something like this:

const [value, setValue] = useState(fromValue);

useEffect(() => {
  setValue(fromValue);
}, [fromValue]);

I initially disliked that the value gets set 2x on the first render, so I had sometimes opted to initialize the state to null or undefined.

const [value, setValue] = useState(null);

useEffect(() => {
  setValue(initialValue);
}, [initialValue]);

The downside of this is that an extra render occurs when state gets set in the useEffect callback. It turns out that this is not the case when setting the value in both places, since the setValue call won't trigger a re-render if the state has not actually changed.

I'm a big fan of breaking out custom hooks when possible to keep components cleaner, more testable, etc., so I decided to do so here.

export function useDependentState<D>(
  dependency: D
): [D, (data: D) => void] {
  const [state, setState] = useState<D>(
    dependency,
  );

  useEffect(() => {
    setState(dependency);
  }, [dependency]);

  return [
    state,
    setState,
  ];
}

This also has the benefit of being reusable. It will probably become a hook I use in most of my apps.

Top comments (0)