bigbabyweb
bigbabyweb

Reputation: 388

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

Upvotes: 10

Views: 4374

Answers (2)

stackchain
stackchain

Reputation: 81

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.

Upvotes: 5

HMR
HMR

Reputation: 39340

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.

Upvotes: 5

Related Questions