With react hooks now available should I in case of functional components wrap every function passed with props with useCallback and every other props value with useMemo?
Also having custom function inside my component dependent on any props value should I wrap it with useCallback?
What are good practices to decide which props or const values from component wrap with this hooks ?
If this improves performance why not to do it at all times ?
Lets consider custom button where we wrap click handler and add custom logic
function ExampleCustomButton({ onClick }) { const handleClick = useCallback( (event) => { if (typeof onClick === 'function') { onClick(event); } // do custom stuff }, [onClick] ); return <Button onClick={handleClick} />; }
Lets consider custom button where we wrap click handler and add custom logic on condition
function ExampleCustomButton({ someBool }) { const handleClick = useCallback( (event) => { if (someBool) { // do custom stuff } }, [someBool] ); return <Button onClick={handleClick} />; }
Should i in this two cases wrap my handler with useCallback ?
Similar case with use memo.
function ExampleCustomButton({ someBool }) { const memoizedSomeBool = useMemo(() => someBool, [someBool]) const handleClick = useCallback( (event) => { if (memoizedSomeBool) { // do custom stuff } }, [memoizedSomeBool] ); return <Button onClick={handleClick} />; }
In this example I even pass memoized value to useCallback.
Another case what if in the component tree many components memoize same value ? How does this impact performance ?
And useMemo gives you referential equality between renders for values. useCallback and useMemo both expect a function and an array of dependencies. The difference is that useCallback returns its function when the dependencies change while useMemo calls its function and returns the result.
Why not use useMemo everywhere then? In short, it's not a free performance optimisation. There's an additional cost (memory usage, for one) incurred when setting up useMemo , that can very quickly outweigh the performance benefit of remembering every single function's possible value.
The React useMemo Hook returns a memoized value. Think of memoization as caching a value so that it does not need to be recalculated. The useMemo Hook only runs when one of its dependencies update.
Not worth it, for multiple reasons:
To put all together - you'd waste more time typing all the hooks than a user would gain on having them in the application if you want to put them everywhere. The good old rule applies: Measure, then optimize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With