Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I memoize functions in custom hook?

I have the counter component. I encapsulated the business logic with custom hook. Should I optimize functions by means useCallback? If there is input onchange handler, will the situation be the same?

const increment = () => {
    setCount(count + 1);
};

const increment = useCallback(() => {
    setCount(count + 1);
}, [count]);

Sand

like image 239
bigbabyweb Avatar asked Nov 21 '19 12:11

bigbabyweb


People also ask

What is the best practice to use function useState hook?

Instead, always use Hooks at the top level of your React function, before any early returns. By following this rule, you ensure that Hooks are called in the same order each time a component renders. That's what allows React to correctly preserve the state of Hooks between multiple useState and useEffect calls.

Should I memoize my React components?

If you have a particularly heavy component then it is best to memoize it, but don't memoize every component. Memoization uses memory and can be less performant in certain cases. When a component is memoized, instead of re-rendering it, React diffs the component's new props with its previous props.

Can I use useContext in custom hook?

Create the useContextInside of this custom hook, we'll be using the useContext hook, that allows us to access both the theme and the setTheme function outside of this file. If useContext fails to create a context, it'll return undefined because we forgot the wrap our App or component in a ThemeProvider.


2 Answers

Assuming that count and setCount came from const [count,setCount] = useState(0) then you should use callback in the following way so increment function stays the same during the component's life cycle:

const increment = useCallback(() => setCount(count => count + 1),[]);

You don't need to re create increment when count changes because you can pass a callback to the state setter function.

like image 50
HMR Avatar answered Oct 22 '22 04:10

HMR


Every function declared within a functional component’s scope should be memoized or cached with useCallback. If it references to other variables or functions from the component scope it should list them in its dependency list. Otherwise every prop/state change will be recreating the function a behavior rarely used.

But remember to measure before optimizing. - Even the oficial documentation says to go easy on that.

like image 5
stackchain Avatar answered Oct 22 '22 04:10

stackchain