Previous part: React Hooks Cheat Sheet Part-1
This second part builds on the fundamentals and explores advanced hooks. These hooks help you optimize performance, control child components, and even build your own reusable tools.
We will cover:
useMemo
useCallback
useImperativeHandle
useLayoutEffect
Custom Hooks
Introduction
As your React app grows, performance and reusability become critical. Advanced hooks provide powerful tools to tackle unnecessary re-renders, optimize expensive computations, and share logic without repeating code. Let’s break them down one by one.
1. useMemo
The useMemo hook memoizes the result of a computation. It is useful for expensive calculations that you do not want to recompute on every render.
import React, { useState, useMemo } from "react";
function ExpensiveCalculation({ num }) {
const compute = (n) => {
console.log("Running expensive calculation...");
return n * 1000;
};
const result = useMemo(() => compute(num), [num]);
return <p>Result: {result}</p>;
}
Without useMemo
, the calculation would run on every render, even if num
did not change.
2. useCallback
The useCallback hook memoizes a function, so that child components relying on that function do not re-render unnecessarily.
import React, { useState, useCallback } from "react";
function Button({ onClick, children }) {
console.log("Rendering button:", children);
return <button onClick={onClick}>{children}</button>;
}
function App() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
setCount(prev => prev + 1);
}, []);
return (
<div>
<p>Count: {count}</p>
<Button onClick={handleClick}>Increment</Button>
</div>
);
}
Here, useCallback
prevents the function from being recreated on every render.
3. useImperativeHandle
The useImperativeHandle hook lets you customize the instance value that is exposed when using ref
. This is useful when building reusable components like modals or inputs.
import React, { useRef, forwardRef, useImperativeHandle } from "react";
const CustomInput = forwardRef((props, ref) => {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
focus: () => {
inputRef.current.focus();
}
}));
return <input ref={inputRef} {...props} />;
});
function App() {
const inputRef = useRef();
return (
<div>
<CustomInput ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
</div>
);
}
This gives you controlled access to internal component methods.
4. useLayoutEffect
The useLayoutEffect hook runs synchronously after all DOM mutations but before the browser paints. Use it when you need to measure the DOM or update the layout before the user sees it.
import React, { useLayoutEffect, useRef } from "react";
function Box() {
const boxRef = useRef();
useLayoutEffect(() => {
console.log("Box width:", boxRef.current.offsetWidth);
}, []);
return <div ref={boxRef} style={{ width: "200px", height: "100px", background: "lightblue" }}>Box</div>;
}
Use this hook sparingly, since it can block rendering if overused.
5. Custom Hooks
Custom hooks let you extract reusable logic. For example, a hook to detect window size:
import { useState, useEffect } from "react";
function useWindowSize() {
const [size, setSize] = useState({
width: window.innerWidth,
height: window.innerHeight
});
useEffect(() => {
function handleResize() {
setSize({
width: window.innerWidth,
height: window.innerHeight
});
}
window.addEventListener("resize", handleResize);
return () => window.removeEventListener("resize", handleResize);
}, []);
return size;
}
And how to use it:
function App() {
const { width, height } = useWindowSize();
return (
<p>Window size: {width} x {height}</p>
);
}
Custom hooks are just functions that use other hooks, which makes them a powerful way to organize and reuse logic.
Wrapping Up Part 2
In this part, we covered advanced hooks and showed how they can make your React apps faster and more maintainable. useMemo
and useCallback
help with performance, useImperativeHandle
gives more control to component authors, useLayoutEffect
handles DOM measurements, and custom hooks let you build reusable tools tailored to your project.
Together with the fundamentals from Part 1, you now have a complete cheat sheet that you can rely on whenever you are working with React Hooks.