constApp=()=>{const[value,setValue]=useState(1);const[value1,setValue1]=useState(1);consthandlers=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(<divclassName="app"><buttononClick={handlers.handleClick}>Iwillnottriggerexpensivere-render</button>
<buttononClick={()=>setValue1(value1+1)}>Iwillnottriggerexpensivere-render</button>
</div>
);};
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.
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 ¯\_(ツ)_/¯
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
play with this code and see where it goes wrong
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.
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¯\_(ツ)_/¯