DEV Community

Discussion on: React hooks & the closure hell

Collapse
 
robchristian profile image
Rob Christian • Edited

This is a lot more code than you need. Taking your original sample, put value into a ref from useRef, and inside the useCallback function, get value from your ref. Also, don't use [value] as a dependency, use only [] dependencies, this way it only runs once.

const App = () => {
  const [value, setValue] = useState(1);
  const valueRef = useRef(value);
  valueRef.current = value;


  const handleClick = useCallback(
    () => {
      setValue(valueRef.current + 1)
    },
    [],
  );