DEV Community

Discussion on: React hooks & the closure hell 2

Collapse
 
stereobooster profile image
stereobooster • Edited

play with this code and see where it goes wrong


const App = () => {
  const [value, setValue] = useState(1);
  const [value1, setValue1] = useState(1);

  const handlers = useCallbacks(callbacks => {
    console.log('here')
    callbacks.handleClick = (event) => {
      setValue(value + 1)
    }
  })

  // Check console, the state has changed so the App function will re-run
  // but memoized ExpensiveComponent won't be called because the actual handling
  // function hasn't changed.
  console.log(value)

  return (
    <div className="app">
      <button onClick={handlers.handleClick}>
        I will not trigger expensive re-render
      </button>
      <button onClick={() => setValue1(value1 + 1) }>
        I will not trigger expensive re-render
      </button>
    </div>
  );
};
Collapse
 
anpos231 profile image
anpos231 • Edited

I think I am missing what you are trying to accomplish here? For me everything works as expected.

If you want to know why is console.log('here') being called? It's because callbacks are regenerated on each render, this way you can always access fresh values from your closure. But values inside the handlers object are always the same, so you are passing the same value to your components.

To visualise:
[handler] calls [callback]

[callback] changes on each render
[handler] always stays the same

[handler] is what you are passing to your descendant components.
[callback] is the function that does stuff.

Collapse
 
stereobooster profile image
stereobooster • Edited

If I will click second button, I will see here in the console e.g. function in your hook gets recreated even though state connected to it isn't changed. But I see from the comment, that this is exactly what you want ¯\_(ツ)_/¯