DEV Community

Discussion on: React hooks & the closure hell 2

Collapse
 
robchristian profile image
Rob Christian • Edited

You don't need to put the handlers into your ref. I provided the following example in a reply to your previous post. You can solve this with a simple 4-line change, which will also be a lot easier for other developers to understand and work with.

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


  const handleClick = useCallback(
    () => {
      setValue(valueRef.current + 1) // this was updated
    },
    [], // this was updated
  );
Collapse
 
anpos231 profile image
anpos231

I see.
My solution was is definitely not the best one here.

I'd like to encourage you to check @shiatsumat answer above. It's probably the cleanest way to approach this problem, this method was even mentioned in the official react docs!

The problem with your solution is that it's not clear what valueRef.current is and how to handle it. Some developers might try setting valueRef.current directly, and be surprised that it does not work.

@shiatsumat solution allows you to write the code like this, but without valueRef. Just a single custom hook.