DEV Community

tingyuan
tingyuan

Posted on • Edited on

a new way to use state in react

In Reactjs, when you want to read or write the latest value of state data in your component, but do not want to specify them as dependencies(such as their change does not matter), you could use the custom hook function below.

Keep in mind that the only reason to specify dependencies in useEffect is because your effect callback need to re-run when anyone of the dependencies changes and the only reason why using useEffect is that you are not sure when the dependencies will change in the component.

export function useGetState(data) {
  const [val, setVal] = React.useState(data);
  const currentValRef = React.useRef(val);
  currentValRef.current = val;
  return React.useCallback((...args) => {
    if (args.length) {
      setVal(args[0]);
    } else {
      return currentValRef.current;
    }
  }, []);
}
Enter fullscreen mode Exit fullscreen mode

There is an example

Top comments (0)