When should we worry about functional components redefining variables and functions??
I think this first case is clearly unnecessary, functions is not expensive to create(and the react dev tools profile test didn't detect performace change with useCallback)
import React, { useState, useMemo, useCallback } from "react";
export const App = () => {
const [counter, setCounter] = useState(1);
const showCounter = useCallback(() => {
console.log(counter);
}, [counter]);
return (
<>
<button onClick={showCounter}>Show</button>
<button onClick={() => setCounter(counter + 1)}>Add</button>
</>
);
};
In the other hand, in this other exemple, with react dev tools we can detect that useMemo cuts in half the time of rendering:
import React, { useState, useMemo, useCallback } from "react";
export const App = () => {
const [counter, setCounter] = useState(1);
const [list, setList] = useState<number[]>([]);
function setListItem(item: number) {
setList([...list, item]);
}
//should we useMemo here?
const domList = useMemo(
() =>
list.map((value: number, index: number) => (
<li key={index}> {value} </li>
)),
[list]
);
return (
<>
<p>{counter}</p>
<button onClick={() => setCounter(counter - 1)}>Subtract</button>
<button onClick={() => setCounter(counter + 1)}>Add</button>
<button onClick={() => setListItem(counter)}>Push to array</button>
<h1>List</h1>
<ul>{domList}</ul>
</>
);
};
But still less than a millisecond of gain and array maps and JSX array are not something really expensive when we talk about front-end either. However, leaving an array map method run in each render is very uncomfortable to see. So, what of those things should we do? (Let's forget about when we have useEffect that depends of some variables that make the useMemo necessary)
- useCallback and useMemo in all functions and variables that don't need to be redefined in each render.
- useCallback and useMemo only in things that we can clearly see a performance gain(even if most time would not count as an improvement to UX). So we would need useMemo in this second example.
- useCallback and useMemo only when not using it in a specific case we would get a great UX decline. So only really expensive functions would useCallback