Choosing the Right Hook in React JS – Complete Detailed Notes
Course: React JS Training
Topic: Choosing the Right Hook
Level: Beginner to Advanced
1. Introduction to React Hooks
React Hooks are special functions that allow functional components to use React features such as state management, side effects, context, references, and performance optimization. Hooks make it easier to organize reusable logic and manage component behavior without using class components.
Choosing the right Hook is an important React development skill. Different Hooks solve different problems. For example, useState manages simple state, useEffect synchronizes a component with external systems, and useRef stores a mutable value or references a DOM element.
A developer should select a Hook based on the problem being solved rather than using Hooks unnecessarily.
Learning Objectives
- Understand the purpose of commonly used React Hooks.
- Identify which Hook is suitable for a particular requirement.
- Understand the differences between similar Hooks.
- Avoid common mistakes when selecting Hooks.
- Apply appropriate Hooks in real-world React applications.
Official reference: React Built-in Hooks Documentation
2. What Does Choosing the Right Hook Mean?
Choosing the right Hook means selecting the React Hook that best matches the behavior your component needs. React provides several Hooks, and each has a specific purpose.
For example, if a component must display a counter that updates when a button is clicked, useState is appropriate. If it must fetch data or subscribe to an external system, an Effect may be needed. If it must access an input element without causing a re-render, useRef is often appropriate.
Simple Examples
| Requirement |
Suitable Hook |
Reason |
| Store a counter value |
useState |
Updates state and re-renders the component when necessary. |
| Manage complex state transitions |
useReducer |
Centralizes state updates in a reducer function. |
| Synchronize with an external system |
useEffect |
Runs synchronization logic after a commit. |
| Measure layout before the browser paints |
useLayoutEffect |
Allows layout measurement and visual correction before repaint. |
| Store a DOM element reference |
useRef |
Provides a persistent ref object. |
| Share data across a component tree |
useContext |
Reads a value from a context provider. |
| Cache an expensive calculation |
useMemo |
Can skip recalculating a value when dependencies have not changed. |
| Cache a function definition |
useCallback |
Can preserve a function definition between renders. |
| Expose selected child methods through a ref |
useImperativeHandle |
Customizes the value exposed through a ref. |
| Reuse stateful logic |
Custom Hook |
Encapsulates reusable logic using Hooks. |
3. Understanding the Main Categories of Hooks
3.1 State Management Hooks
State management Hooks help components store and update data that affects the rendered interface.
useState: manages individual state values such as text, counters, booleans, and form fields.
useReducer: manages state through a reducer function and dispatched actions.
3.2 Effect Hooks
Effect Hooks are used to synchronize a component with systems outside React, such as browser APIs, subscriptions, timers, and network connections.
useEffect: synchronizes with external systems after the component commits, generally allowing the browser to paint first.
useLayoutEffect: runs after DOM changes are committed but before the browser repaints. It is useful for layout measurement and visual corrections that must happen before paint.
useInsertionEffect: primarily intended for CSS-in-JS library authors who need to insert styles before layout Effects run.
3.3 Reference and Imperative Hooks
useRef: stores a mutable value or references a DOM element without causing a re-render when its current value changes.
useImperativeHandle: exposes a customized handle through a ref, such as selected methods on a child component.
3.4 Performance Optimization Hooks
useMemo: caches a calculated value between renders when its dependencies remain unchanged.
useCallback: caches a function definition between renders when its dependencies remain unchanged.
3.5 Context and External Store Hooks
useContext: reads a value from a React context.
useSyncExternalStore: subscribes to an external store in a way that supports React's rendering model.
3.6 Custom Hooks
A Custom Hook is a JavaScript function whose name begins with use and which can call other Hooks. It allows developers to reuse stateful logic across components.
4. When Should You Use useState?
The useState Hook is appropriate when a component needs to store data that changes over time and affects what appears on the screen.
Common Use Cases
- Counter applications.
- Input fields and form values.
- Show and hide controls.
- Selected tabs and menu states.
- Loading indicators and simple status messages.
Syntax
const [state, setState] = useState(initialValue);
Example: Counter
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function increment() {
setCount(currentCount => currentCount + 1);
}
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>Increment</button>
</div>
);
}
export default Counter;
Why Is useState the Right Choice?
The counter value affects the rendered output. When the user clicks the button, updating state tells React to render the component with the new count.
Important: Do not use a regular variable for information that must trigger a re-render when it changes.
5. When Should You Use useReducer?
The useReducer Hook is useful when state updates involve several related actions or when the logic for updating state is easier to understand in a separate reducer function.
Common Use Cases
- Multi-step forms.
- Shopping cart state.
- Complex filters and search settings.
- Several related state transitions.
- State updates that depend on action types.
Syntax
const [state, dispatch] = useReducer(reducer, initialState);
Example: Counter with useReducer
import { useReducer } from "react";
function reducer(state, action) {
switch (action.type) {
case "increment":
return { count: state.count + 1 };
case "decrement":
return { count: state.count - 1 };
case "reset":
return { count: 0 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<h2>Count: {state.count}</h2>
<button onClick={() => dispatch({ type: "increment" })}>
Increment
</button>
<button onClick={() => dispatch({ type: "decrement" })}>
Decrement
</button>
<button onClick={() => dispatch({ type: "reset" })}>
Reset
</button>
</div>
);
}
export default Counter;
Why Is useReducer the Right Choice?
Each action describes what should happen, and the reducer determines the next state. This structure can make complex transitions easier to maintain and test.
For simple independent values, useState is usually easier. Do not switch to useReducer just because a component has more than one state variable.
6. When Should You Use useEffect?
The useEffect Hook is designed to synchronize a component with an external system. Examples include setting up a subscription, connecting to a browser API, starting a timer, or fetching data when appropriate.
Common Use Cases
- Connecting to a WebSocket.
- Setting up and cleaning up event listeners.
- Managing timers or intervals.
- Synchronizing with a third-party widget.
- Fetching data when a component's inputs change, with appropriate loading and error handling.
Syntax
useEffect(() => {
// Synchronize with an external system.
return () => {
// Clean up the synchronization.
};
}, [dependencies]);
Example: Document Title
import { useEffect, useState } from "react";
function PageTitle() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Count
</button>
</div>
);
}
export default PageTitle;
Here, the Effect synchronizes the browser tab's title with the current count.
When Not to Use useEffect
Do not use an Effect for every calculation or state update. If a value can be calculated directly from existing props and state during rendering, calculate it during rendering instead. If an action happens because a user clicked a button, place the action in the event handler when appropriate.
7. When Should You Use useLayoutEffect?
The useLayoutEffect Hook is appropriate when code must measure the layout or correct a visual position before the browser paints the updated screen.
Common Use Cases
- Measuring the dimensions of a DOM element.
- Positioning a tooltip based on its dimensions.
- Correcting a visual layout before the user sees it.
- Reading layout information immediately after a DOM update.
Example
import { useLayoutEffect, useRef, useState } from "react";
function BoxSize() {
const boxRef = useRef(null);
const [width, setWidth] = useState(0);
useLayoutEffect(() => {
if (boxRef.current) {
setWidth(boxRef.current.getBoundingClientRect().width);
}
}, []);
return (
<div>
<div
ref={boxRef}
style={{ width: "250px", padding: "20px", border: "1px solid black" }}
>
Measure this box
</div>
<p>Box width: {width}px</p>
</div>
);
}
export default BoxSize;
useEffect vs useLayoutEffect
| Feature |
useEffect |
useLayoutEffect |
| Primary purpose |
Synchronizing with external systems. |
Layout measurement and visual correction before paint. |
| Timing |
Runs after commit; React generally allows the browser to paint first for non-interaction work. |
Runs after DOM changes are committed and before repaint. |
| Performance |
Generally preferred for ordinary Effects. |
Can block painting and should be used sparingly. |
| Typical example |
Subscription or external connection. |
Measuring an element to position a tooltip. |
Rule: Prefer useEffect unless the code must run before repaint to prevent a visible layout problem.
8. When Should You Use useRef?
The useRef Hook is useful when you need to store a mutable value or access a DOM element without triggering a re-render whenever the ref changes.
Common Use Cases
- Focusing an input.
- Storing a timer identifier.
- Keeping a reference to a DOM element.
- Remembering a mutable value that is not part of the rendered output.
- Accessing a third-party library instance.
Example: Focus an Input
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
function focusInput() {
inputRef.current?.focus();
}
return (
<div>
<input ref={inputRef} placeholder="Enter your name" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
export default FocusInput;
Use useRef instead of state when changing the stored value should not itself cause the UI to update. Use state if the value must be reflected in the rendered interface.
9. When Should You Use useContext?
The useContext Hook allows a component to read a value from a React context. It is useful for sharing information across many components without passing the same props through every intermediate component.
Common Use Cases
- Theme settings.
- Authenticated user information.
- Language or localization settings.
- Shared application preferences.
Example: Theme Context
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function ThemeMessage() {
const theme = useContext(ThemeContext);
return <p>Current theme: {theme}</p>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemeMessage />
</ThemeContext.Provider>
);
}
export default App;
The component reads the nearest provider's value. In modern React, a context can also be provided using <ThemeContext value="dark">; the Provider syntax shown above is compatible with older versions too.
When to Choose useContext
Use context when information is needed by multiple components at different levels of the tree. Do not use it automatically for every prop or every state value. Props remain a clear option for data needed by only a small number of nearby components.
10. When Should You Use useMemo?
The useMemo Hook caches the result of a calculation between renders. React can reuse the cached value while its dependencies remain unchanged.
Common Use Cases
- Expensive filtering or sorting of large lists.
- Complex calculations that are noticeably costly.
- Maintaining a stable object value when that stability is needed for an optimization.
Example: Filtering Products
import { useMemo, useState } from "react";
const products = [
{ id: 1, name: "Laptop" },
{ id: 2, name: "Phone" },
{ id: 3, name: "Keyboard" }
];
function ProductSearch() {
const [query, setQuery] = useState("");
const filteredProducts = useMemo(() => {
return products.filter(product =>
product.name.toLowerCase().includes(query.toLowerCase())
);
}, [query]);
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search products"
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
);
}
export default ProductSearch;
For this small list, memoization is not necessary for performance. The example demonstrates the syntax. In real applications, use useMemo when a calculation is sufficiently expensive or when stable identity supports a meaningful optimization.
11. When Should You Use useCallback?
The useCallback Hook caches a function definition between renders when its dependencies remain unchanged. It is primarily useful when function identity matters to a performance optimization.
Common Use Cases
- Passing a callback to a memoized child component.
- Keeping a callback stable when it is used as a dependency of another Hook.
- Avoiding unnecessary work in carefully optimized component trees.
Example
import { useCallback, useState } from "react";
function SearchButton({ onSearch }) {
return <button onClick={onSearch}>Search</button>;
}
function App() {
const [query, setQuery] = useState("");
const handleSearch = useCallback(() => {
console.log("Searching for:", query);
}, [query]);
return (
<div>
<input
value={query}
onChange={event => setQuery(event.target.value)}
placeholder="Search..."
/>
<SearchButton onSearch={handleSearch} />
</div>
);
}
export default App;
useCallback does not automatically make every component faster. Use it when a stable function identity is useful, rather than wrapping every function by default.
useMemo vs useCallback
| Hook |
What It Caches |
Typical Purpose |
useMemo |
A calculated value. |
Avoid recalculating an expensive result unnecessarily. |
useCallback |
A function definition. |
Keep a callback stable for a relevant optimization. |
12. When Should You Use useImperativeHandle?
The useImperativeHandle Hook customizes the value exposed through a ref. It is useful when a parent component needs to trigger a specific action inside a child component.
Common Use Cases
- Exposing a custom input's focus method.
- Providing a clear or select action for a reusable field.
- Exposing a small set of methods from a custom editor.
- Providing selected imperative controls for a specialized component.
Example
import { useImperativeHandle, useRef } from "react";
function CustomInput({ ref }) {
const inputRef = useRef(null);
useImperativeHandle(ref, () => ({
focus() {
inputRef.current?.focus();
}
}), []);
return <input ref={inputRef} placeholder="Enter text" />;
}
export default CustomInput;
This example uses the React 19 ref-as-prop API. In React 18 and earlier, wrap the component in forwardRef. Use this Hook only when exposing an imperative API is more appropriate than controlling the behavior through props and state.
13. When Should You Create a Custom Hook?
A Custom Hook is useful when the same stateful logic or synchronization behavior needs to be reused in multiple components. It lets you extract logic into a function whose name starts with use.
Common Use Cases
- Managing reusable form logic.
- Tracking online status.
- Sharing browser event-listener logic.
- Managing reusable data-fetching behavior.
- Encapsulating local-storage synchronization.
Example: useOnlineStatus
import { useEffect, useState } from "react";
function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
function handleOnline() {
setIsOnline(true);
}
function handleOffline() {
setIsOnline(false);
}
window.addEventListener("online", handleOnline);
window.addEventListener("offline", handleOffline);
return () => {
window.removeEventListener("online", handleOnline);
window.removeEventListener("offline", handleOffline);
};
}, []);
return isOnline;
}
export default useOnlineStatus;
Using the Custom Hook
import useOnlineStatus from "./useOnlineStatus";
function StatusMessage() {
const isOnline = useOnlineStatus();
return (
<p>
{isOnline ? "You are online" : "You are offline"}
</p>
);
}
export default StatusMessage;
This example is intended for a browser environment. The initial access to navigator.onLine should be adapted if the application also renders on the server.
A Custom Hook shares logic, not one shared state instance. Each component that calls the Hook gets its own Hook state unless the logic connects to a shared store or another shared source.
14. Decision Guide: Which Hook Should You Choose?
Use the following questions to select a Hook based on your actual requirement.
| Question |
Recommended Choice |
| Does the value change and affect the rendered UI? |
useState or useReducer |
| Are state transitions complex or action-based? |
useReducer |
| Do you need to synchronize with an external system? |
useEffect |
| Must you measure or correct layout before repaint? |
useLayoutEffect |
| Do you need a DOM reference or mutable value that does not trigger rendering? |
useRef |
| Do many components need the same contextual value? |
useContext |
| Is a calculation expensive enough to justify caching? |
useMemo |
| Does a stable function identity help an optimization? |
useCallback |
| Does a parent need a specific imperative method from a child? |
useImperativeHandle |
| Do multiple components need reusable stateful logic? |
Custom Hook |
| Do you need to subscribe to an external state store? |
useSyncExternalStore |
15. Hooks You Should Not Use Unnecessarily
15.1 Avoid useEffect for Derived Values
If a value can be calculated from props or state during rendering, you generally do not need to store it in state and update it through an Effect.
Less suitable approach:
const [fullName, setFullName] = useState("");
useEffect(() => {
setFullName(firstName + " " + lastName);
}, [firstName, lastName]);
Better approach:
const fullName = firstName + " " + lastName;
15.2 Avoid useMemo for Every Calculation
Small, inexpensive calculations usually do not need memoization. Start with straightforward code and optimize when there is a real performance reason.
15.3 Avoid useCallback for Every Function
Function definitions are usually inexpensive. Use useCallback when stable identity is useful, such as when working with a memoized child or Hook dependency.
15.4 Avoid useRef for Visible State
If a value must update the interface when it changes, use state rather than relying only on a ref.
15.5 Avoid Context for Every Prop
Props are often the simplest solution when data only needs to travel through a small component hierarchy.
16. Rules of Hooks
Regardless of which Hook you choose, you must follow React's Rules of Hooks.
- Call Hooks at the top level of a function component or custom Hook.
- Do not call Hooks inside loops, conditions, or nested functions.
- Call Hooks only from React function components or custom Hooks, not ordinary JavaScript functions.
- Keep Hook calls in the same order on every render.
- Include all relevant reactive dependencies in Effect and memoization dependency arrays.
- Use the React Hooks lint rules to catch common mistakes.
Official reference: Rules of Hooks
17. Common Mistakes When Choosing Hooks
| Mistake |
Why It Is a Problem |
Better Approach |
| Using useEffect for every operation. |
Creates unnecessary synchronization and additional renders. |
Calculate derived values during rendering and use event handlers for user actions. |
| Using useRef for UI state. |
Changing the ref does not trigger a re-render. |
Use useState or useReducer for values that affect rendering. |
| Using useReducer for trivial state. |
Adds structure that may not be needed. |
Use useState for simple state updates. |
| Using useMemo for every expression. |
Can add complexity without a meaningful performance benefit. |
Memoize only when there is a clear reason. |
| Using useCallback without a reason. |
Can make code harder to read without improving performance. |
Use it when stable function identity matters. |
| Using useLayoutEffect instead of useEffect by default. |
May block the browser from painting. |
Use it only for pre-paint layout work. |
| Using context for every value. |
Can obscure data flow and broaden dependencies. |
Prefer props when appropriate. |
| Creating a custom Hook for one simple expression. |
Can add unnecessary abstraction. |
Extract logic when reuse or clearer organization justifies it. |
18. Practical Project: React Task Management Application
Project objective: Build a small task management application that uses the right Hooks for state, effects, references, and reusable logic.
Project Features
- Add new tasks.
- Mark tasks as completed.
- Delete tasks.
- Display task counts.
- Focus the task input after adding a task.
- Save tasks to local storage.
- Share theme settings across components.
Recommended Hook Selection
| Feature |
Hook |
Reason |
| Task list |
useState or useReducer |
Stores tasks and updates the rendered list. |
| Task input focus |
useRef |
References the input DOM element. |
| Local storage synchronization |
useEffect |
Synchronizes task data with browser storage. |
| Shared theme |
useContext |
Provides theme information to multiple components. |
| Expensive task filtering |
useMemo, if needed |
Can cache a costly filtered result. |
| Reusable task logic |
Custom Hook |
Extracts reusable stateful behavior. |
Project Development Steps
- Create the React application and organize its components.
- Implement task state using
useState or useReducer.
- Create task input and list components.
- Use
useRef to focus the input after adding a task.
- Use
useEffect to synchronize the task list with local storage.
- Add a context provider if theme information is shared across many components.
- Extract repeated behavior into a Custom Hook when appropriate.
- Test the application's behavior and optimize only where necessary.
19. Interview Questions and Answers
Q1. What are React Hooks?
Answer: Hooks are functions that let function components use React features such as state, context, refs, Effects, and performance optimizations.
Q2. Which Hook is used to manage state?
Answer: useState is used for simple state, while useReducer is useful for more complex or action-based state transitions.
Q3. What is the difference between useState and useReducer?
Answer: useState provides a state value and setter. useReducer provides state and a dispatch function that sends actions to a reducer.
Q4. When should useEffect be used?
Answer: Use it to synchronize a component with external systems, such as subscriptions, timers, browser APIs, or external connections.
Q5. What is the difference between useEffect and useLayoutEffect?
Answer: useEffect is suitable for most synchronization work. useLayoutEffect runs before repaint and is useful for layout measurement or visual correction that must happen before the user sees the screen.
Q6. Why is useRef different from useState?
Answer: Updating ref.current does not trigger a re-render, while updating state schedules a render when React determines the state has changed.
Q7. What is useContext used for?
Answer: It reads a value from a context provider and helps share information across components without manually passing props through every intermediate level.
Q8. What is the difference between useMemo and useCallback?
Answer: useMemo caches a calculation result, while useCallback caches a function definition.
Q9. When should a developer create a Custom Hook?
Answer: Create one when stateful logic or synchronization behavior should be reused across components or when extracting the logic improves clarity.
Q10. What is useImperativeHandle used for?
Answer: It customizes the value exposed through a ref, allowing a child component to provide selected methods to a parent.
Q11. Should useMemo and useCallback always be used for performance?
Answer: No. They should be used when caching or stable identity provides a meaningful benefit. Unnecessary memoization can add complexity.
Q12. Can Hooks be called inside conditions?
Answer: No. Hooks must be called at the top level of React function components or custom Hooks so their call order remains consistent.
Q13. Which Hook is useful for an external store?
Answer: useSyncExternalStore is designed to subscribe to an external store while supporting React's rendering behavior.
Q14. Which Hook should be used for a form?
Answer: useState is suitable for simple form fields. useReducer may be useful for complex forms with related transitions. Custom Hooks can encapsulate reusable form logic.
Q15. How do you decide which Hook is best?
Answer: Identify the requirement first: state, external synchronization, DOM access, shared context, expensive calculation, stable callback, imperative child control, or reusable logic. Then select the simplest Hook that correctly solves the problem.
20. Practice Exercises
- Create a counter using
useState.
- Rewrite the counter using
useReducer.
- Build a component that updates the document title with
useEffect.
- Create an input field that can be focused using
useRef.
- Build a theme context and read its value with
useContext.
- Use
useMemo to cache an expensive calculation.
- Use
useCallback when passing a callback to a memoized child component.
- Create a Custom Hook that tracks the browser's online status.
- Build a reusable input that exposes a focus method through
useImperativeHandle.
- Review an existing component and remove Effects or memoization that are not necessary.
21. Quick Revision Checklist
useState manages simple component state.
useReducer manages action-based or complex state transitions.
useEffect synchronizes with external systems.
useLayoutEffect supports layout measurement and visual correction before repaint.
useRef stores mutable values or references DOM elements.
useContext reads shared contextual values.
useMemo caches calculated values when useful.
useCallback caches function definitions when useful.
useImperativeHandle customizes the value exposed through a ref.
- Custom Hooks reuse stateful logic.
useSyncExternalStore subscribes to external stores.
- Choose Hooks according to the requirement, not simply because they are available.
- Follow the Rules of Hooks and manage dependencies correctly.
22. Official React Learning Resources
23. React JS Training and Course Demo
Learn React fundamentals, Hooks, component architecture, state management, reusable logic, and practical application development through the following resources.
JustAcademy React JS Training
Register for React JS Course Demo
24. Conclusion
Choosing the right Hook is essential for writing clean, maintainable, and efficient React applications. Each Hook has a specific purpose, and understanding those purposes helps developers avoid unnecessary complexity.
Use useState for simple state, useReducer for complex state transitions, useEffect for external synchronization, useRef for mutable values and DOM references, and useContext for shared contextual data. Use memoization Hooks when they provide a meaningful benefit, and create Custom Hooks when reusable stateful logic improves the code.
Final takeaway: Understand the problem first, choose the simplest suitable Hook, and keep your React components declarative wherever possible.