DEV Community

Discussion on: React hooks & the closure hell

Collapse
 
alexpanchuk profile image
Alex Panchuk

How about this one?

function useStateWithGetter(initial) {
  const ref = useRef(initial);
  const [state, setState] = useState(initial);

  useEffect(() => {
    ref.current = state
  }, [state])

  const getValue = useCallback(() => {
    return ref.current;
  }, []);

  return [state, setState, getValue];
}

// ...

const [, setValue, getValue] = useStateWithGetter(1);

const handleClick = useCallback(() => {
  const value = getValue();
  setValue(value + 1);
}, [getValue, setValue]);
Enter fullscreen mode Exit fullscreen mode