3 ms·
I was never able to understand what useCallback does.
by koakuma-chan 2y ago
I was never able to understand what useCallback does.
- fancyswimtime 2y agoits all about scope
- null_deref 2y agoIt’s used in order to prevent redundant rerender to child components. When passing to a child component a function you’ve created inside functional component it’s get recreated because JS doesn’t keep references to a function created inside a function, thus making your child component rerender because a prop has changed. This example actually really corresponds with this post comments, the need for useCallback have only emerged after the move from class components, because private methods you create in a class do not get recreated at each render
- koito17 2y agoAnonymous functions are not primitive values, so JavaScript passes them as pointers. React uses strict equality when comparing props, so non-primitive values are compared with pointer equality. The useCallback hook allows one to cache anonymous functions in order to pass stable pointers as props and avoid re-renders from pointers changing. It's the exact same motivation as useMemo for passing props with "stable identity".
- Cthulhu_ 2y agoPrevents some re-renders when passing callbacks down the render chain, but the core flaw in modern day React is that this is added to the developer's list of things to worry about (same as memoization) and manage with the dependency array. It just feels like a lot of things that the framework should deal with and abstract away.
- koakuma-chan 2y agoYeah that's crazy that function pointers cause re-renders in React, I had no idea about this. My go-to reactivity library is SolidJS right now though, their fine-grained reactivity is really nice to work with.