Skip to main content

useMemo and useCallback Hooks in React (Live Playground)

React's useMemo and useCallback hooks help optimize the performance of functional components by preventing unnecessary renders and recalculations. In this tutorial, we'll cover the basics of these hooks and how to use them in your React applications.

useMemo

The useMemo hook allows you to memoize the result of an expensive calculation so that it doesn't need to be recalculated on every render.

Using useMemo

JavaScript
import React, { useState, useMemo } from 'react';

function calculateFactorial(num) {
if (num <= 1) return 1;
return num * calculateFactorial(num - 1);
}

function App() {
const [number, setNumber] = useState(5);

const factorial = useMemo(() => calculateFactorial(number), [number]);

return (
<div>
<input type="number" value={number} onChange={e => setNumber(parseInt(e.target.value))} />
<p>Factorial: {factorial}</p>
</div>
);
}

export default App;

In this example, useMemo is used to memoize the result of calculateFactorial(number) so that the calculation is only performed when number changes.

Live Playground, Try it Yourself

useCallback

The useCallback hook allows you to memoize a function to prevent it from being recreated on every render, which can help prevent unnecessary re-renders of child components.

Using useCallback

JavaScript
import React, { useState, useCallback } from 'react';

const MyButton = React.memo(function Button({ onClick, children }) {
console.log('Button rendered:', children);
return <button onClick={onClick}>{children}</button>;
});

function App() {
const [count, setCount] = useState(0);

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

console.log('App rendered');
return (
<div>
<p>Count: {count}</p>
<MyButton onClick={increment}>Increment</MyButton>
</div>
);
}

export default App;

In this example, useCallback is used to memoize the increment function so that the Button component only re-renders when necessary. Need to work with React.memo together to prevent unnecessary re-renders of Button component.

Live Playground, Try it Yourself

Conclusion

useMemo and useCallback hooks are powerful tools for optimizing the performance of your React functional components. By using these hooks, you can prevent unnecessary re-renders and recalculations, which can improve the performance of your application. Make sure to use these hooks wisely, as excessive use can lead to increased memory usage and reduced performance.