Learn about React Hooks
###useCallback & useMemo
When to useMemo and useCallback Performance optimizations are not free. They ALWAYS come with a cost but do NOT always come with a benefit to offset that cost.
So when should I useMemo and useCallback? There are specific reasons both of these hooks are built-into React:
- Referential equality
- Computationally expensive calculations
React.memo and React.useCallback must remember that they need to be paired. The lack of one may cause the performance to not increase but to "decrease". After all, a meaningless shallow comparison also consumes a little bit of performance.
Endless looping:
let count = 0;
function App() {
const [val, setVal] = useState("");
function getData() {
setTimeout(() => {
setVal("new data " + count);
count++;
}, 500);
}
return <Child val={val} getData={getData} />;
}
function Child({val, getData}) {
useEffect(() => {
getData();
}, [getData]);
return <div>{val}</div>;
}
useCallback():
const getData = useCallback(() => {
setTimeout(() => {
setVal("new data " + count);
count++;
}, 500);
}, []);