Introduction to React Hooks
React Hooks are special functions that allow functional components to use React features such as state, side effects, context, references, and performance optimizations. Hooks make it easier to manage component logic and reuse stateful behavior without writing class components.
React introduced Hooks in React 16.8. Today, Hooks are an important part of modern React development and are widely used to build interactive user interfaces.
Course: JustAcademy React JS Training
Course Demo: Register for React JS Course Demo
1. Learning Objectives
After studying this topic, you will be able to:
- Understand the meaning and purpose of React Hooks.
- Explain why Hooks are used in functional components.
- Understand the difference between class components and functional components.
- Use the basic Hooks such as
useState and useEffect.
- Recognize other commonly used Hooks, including
useContext, useRef, useMemo, and useCallback.
- Follow the Rules of Hooks.
- Create simple React applications using Hooks.
2. What Are React Hooks?
React Hooks are built-in React functions that let function components access and use React features. A Hook typically has a name beginning with the word use, such as useState, useEffect, or useContext.
Before Hooks were introduced, developers commonly used class components to manage state and lifecycle-related behavior. Hooks made it possible to use many of these capabilities directly in function components.
Example of a React Hook
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(count + 1)}>
Increase
</button>
</div>
);
}
export default Counter;
Explanation:
useState(0) creates a state variable with an initial value of 0.
count contains the current state value.
setCount is the function used to update that state.
- When the button is clicked, the state changes and React renders the updated count.
3. Why Do We Need React Hooks?
React applications frequently need to remember user input, display dynamic information, respond to changes, and communicate with external systems. Hooks provide a structured way to handle these requirements inside function components.
Main Reasons for Using Hooks
- State management: Store and update values such as counters, form data, selected tabs, and shopping cart items.
- Side-effect management: Synchronize components with external systems, such as browser APIs, timers, and subscriptions.
- Reusable logic: Extract shared behavior into custom Hooks that can be used by multiple components.
- Cleaner components: Organize related logic without requiring class component syntax.
- Context access: Read shared values such as themes, authentication information, and language preferences.
- Performance optimization: Cache expensive calculations or function definitions when appropriate.
Example Without and With Hooks
In a class component, state is commonly accessed through this.state and updated with this.setState(). With Hooks, a function component can use useState() to manage its own state.
// Using Hooks
import { useState } from "react";
function Greeting() {
const [name, setName] = useState("Student");
return (
<div>
<h2>Hello, {name}!</h2>
<button onClick={() => setName("React Developer")}>
Change Name
</button>
</div>
);
}
In this example, clicking the button updates the state and changes the displayed greeting without manually manipulating the DOM.
4. Important Features of React Hooks
- Hooks are JavaScript functions provided by React or created by developers.
- Most Hooks must be called at the top level of a function component or another custom Hook.
- Hooks help manage state and synchronize components with external systems.
- Hooks can be combined to create reusable functionality.
- Updating state can cause React to render a component again.
- Hooks work with function components; they cannot be called directly inside class components.
- Hooks do not automatically make an application faster. Performance Hooks should be used when there is a meaningful optimization need.
5. Types of React Hooks
React provides different Hooks for different purposes. The following table introduces several commonly used Hooks.
| Hook |
Purpose |
Common Use Case |
useState |
Stores and updates component state. |
Counter, form fields, toggles. |
useEffect |
Synchronizes a component with external systems. |
Event subscriptions, timers, API synchronization. |
useContext |
Reads values from React Context. |
Theme, language, authentication information. |
useRef |
Stores a value that persists between renders without triggering a render when changed. |
DOM access, interval IDs, previous values. |
useReducer |
Manages state using a reducer function. |
Complex forms, multi-step state transitions. |
useMemo |
Caches the result of a calculation. |
Expensive filtering or calculations. |
useCallback |
Caches a function definition between renders when dependencies remain unchanged. |
Passing callbacks to memoized child components. |
useLayoutEffect |
Runs an effect before the browser repaints the screen. |
Measuring DOM layout when timing matters. |
useId |
Generates IDs suitable for accessibility relationships. |
Connecting labels and form controls. |
useTransition |
Marks certain state updates as non-urgent transitions. |
Keeping an interface responsive during larger updates. |
useDeferredValue |
Defers updating a value used by non-urgent UI. |
Expensive search results or filtered displays. |
| Custom Hooks |
Reuse stateful logic between components. |
Window size, online status, reusable form behavior. |
Note: You do not need to learn every Hook at once. Start with useState and useEffect, then learn other Hooks as your application requirements grow.
6. Understanding useState
useState is a React Hook that adds a state variable to a function component. State is data that React remembers between renders.
Syntax
const [state, setState] = useState(initialValue);
state: The current value.
setState: The function used to request a state update.
initialValue: The value used to initialize the state.
Example: Counter Application
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
function increaseCount() {
setCount(previousCount => previousCount + 1);
}
function decreaseCount() {
setCount(previousCount => previousCount - 1);
}
function resetCount() {
setCount(0);
}
return (
<div>
<h2>Counter Application</h2>
<p>Current Count: {count}</p>
<button onClick={increaseCount}>Increase</button>
<button onClick={decreaseCount}>Decrease</button>
<button onClick={resetCount}>Reset</button>
</div>
);
}
export default Counter;
How It Works
- The component initializes
count to 0.
- React displays the current value.
- Clicking Increase requests an increment.
- Clicking Decrease requests a decrement.
- Clicking Reset requests a value of
0.
- React renders the updated value.
Why Use a Functional State Update?
When the next state depends on the previous state, use the updater function form. It helps React apply updates using the latest queued state value.
setCount(previousCount => previousCount + 1);
For example, this is generally more reliable for repeated increments than calculating several updates from a potentially outdated value.
7. Understanding useEffect
useEffect allows a component to synchronize with an external system. Examples include setting up a timer, subscribing to browser events, connecting to a service, or updating the document title.
Basic Syntax
useEffect(() => {
// Synchronization logic
return () => {
// Optional cleanup logic
};
}, [dependencies]);
The dependency array tells React which reactive values the effect depends on. React reruns the effect when those dependencies change. If setup creates a subscription, timer, or connection, a cleanup function should usually remove or disconnect it.
Example: Updating the Document Title
import { useEffect, useState } from "react";
function ClickCounter() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Clicks: ${count}`;
}, [count]);
return (
<div>
<h2>Clicks: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Click Me
</button>
</div>
);
}
export default ClickCounter;
Explanation: Whenever count changes, the effect updates the browser tab title. Because the effect uses count, that value is included in the dependency array.
Understanding Dependency Arrays
| Pattern |
Meaning |
useEffect(() => { ... }); |
Runs after every committed render. |
useEffect(() => { ... }, []); |
Runs after the initial mount; development Strict Mode may run an additional setup-and-cleanup cycle. |
useEffect(() => { ... }, [value]); |
Runs after the initial mount and again when the dependency changes. |
Do not use an effect for every calculation or event. If a value can be calculated directly from props or state during rendering, an effect may be unnecessary.
8. Understanding useContext
useContext lets a component read a value from React Context without passing that value through every intermediate component as props.
Example: Theme Context
import { createContext, useContext } from "react";
const ThemeContext = createContext("light");
function ThemeDisplay() {
const theme = useContext(ThemeContext);
return <h2>Current Theme: {theme}</h2>;
}
function App() {
return (
<ThemeContext.Provider value="dark">
<ThemeDisplay />
</ThemeContext.Provider>
);
}
export default App;
Explanation: The provider supplies the value "dark". The ThemeDisplay component reads that value using useContext.
Common uses: Theme settings, language preferences, authentication details, and other shared application values.
9. Understanding useRef
useRef creates a reference object whose current property persists between renders. Updating this property does not itself trigger a re-render.
Example: Focus an Input
import { useRef } from "react";
function FocusInput() {
const inputRef = useRef(null);
function handleFocus() {
inputRef.current?.focus();
}
return (
<div>
<input ref={inputRef} placeholder="Enter your name" />
<button onClick={handleFocus}>Focus Input</button>
</div>
);
}
export default FocusInput;
Here, useRef stores a reference to the input element. Clicking the button focuses the input field.
Important: Use state when a value needs to appear in the rendered UI and should trigger an update. Use a ref when you need to retain a value without triggering a render, or when you need access to a DOM element.
10. Understanding useReducer
useReducer is useful when state transitions involve multiple actions or more complex logic. It uses a reducer function to calculate the next state from the current state and an action.
Example: Counter Using 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" })}>Increase</button>
<button onClick={() => dispatch({ type: "decrement" })}>Decrease</button>
<button onClick={() => dispatch({ type: "reset" })}>Reset</button>
</div>
);
}
export default Counter;
Explanation: The reducer defines how each action changes the state. The dispatch function sends an action to the reducer.
11. Understanding useMemo
useMemo caches the result of a calculation between renders while its dependencies remain unchanged. It can help avoid repeating expensive calculations unnecessarily.
Example: Filtering Products
import { useMemo, useState } from "react";
const products = [
{ id: 1, name: "Laptop", price: 50000 },
{ id: 2, name: "Mouse", price: 800 },
{ id: 3, name: "Keyboard", price: 1500 }
];
function ProductList() {
const [search, setSearch] = useState("");
const filteredProducts = useMemo(() => {
return products.filter(product =>
product.name.toLowerCase().includes(search.toLowerCase())
);
}, [search]);
return (
<div>
<input
value={search}
onChange={event => setSearch(event.target.value)}
placeholder="Search products"
/>
<ul>
{filteredProducts.map(product => (
<li key={product.id}>{product.name} - ₹{product.price}</li>
))}
</ul>
</div>
);
}
export default ProductList;
Explanation: The filtered list is recalculated when search changes. For a tiny list, memoization may not be necessary; it is more useful when a calculation is expensive or profiling identifies a performance issue.
12. Understanding useCallback
useCallback caches a function definition until its dependencies change. It is mainly useful when function identity matters, such as when passing a callback to a memoized child component.
Example
import { useCallback, useState } from "react";
function ActionButton({ onAction }) {
return <button onClick={onAction}>Run Action</button>;
}
function App() {
const [count, setCount] = useState(0);
const handleAction = useCallback(() => {
console.log("Action performed");
}, []);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(c => c + 1)}>Increase</button>
<ActionButton onAction={handleAction} />
</div>
);
}
export default App;
Explanation: The callback retains the same function identity while its dependencies remain unchanged. This alone does not prevent a child from rendering; pairing it with an appropriate optimization such as memo may be useful when performance measurements justify it.
13. What Are Custom Hooks?
A custom Hook is a JavaScript function created by a developer to reuse logic that uses React Hooks. Its name should begin with use, followed by a descriptive name.
Custom Hooks share logic, not automatically the same state instance. Each component calling a custom Hook normally gets its own Hook state unless the logic connects to a shared store or context.
Example: Custom Hook for Online Status
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;
}
function NetworkStatus() {
const isOnline = useOnlineStatus();
return <h2>Status: {isOnline ? "Online" : "Offline"}</h2>;
}
export default NetworkStatus;
Explanation: The custom Hook checks the browser's connection status, listens for online and offline events, and removes event listeners during cleanup.
Other custom Hook ideas: useWindowSize, useLocalStorage, useDebounce, and useForm.
14. Rules of React Hooks
React relies on Hooks being called consistently so that it can associate each Hook with the correct state and behavior. Follow these rules when writing React components.
Rule 1: Call Hooks at the Top Level
Call Hooks at the top level of a function component or custom Hook. Do not call them inside conditions, loops, or nested functions.
// Incorrect
if (isLoggedIn) {
const [name, setName] = useState("");
}
// Correct
const [name, setName] = useState("");
if (isLoggedIn) {
// Use the state here as needed.
}
Rule 2: Call Hooks Only from React Functions
Call Hooks from function components or custom Hooks, not from ordinary JavaScript functions, event handlers, or class components.
// Incorrect
function handleClick() {
const [count, setCount] = useState(0);
}
// Correct
function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(c => c + 1);
}
return <button onClick={handleClick}>Count: {count}</button>;
}
Rule 3: Call Hooks Before Early Returns
Do not place ordinary Hooks after a conditional return that might cause them to be skipped on some renders. Declare the Hooks before conditional return statements.
Rule 4: Keep Hook Dependencies Correct
When using useEffect, useMemo, or useCallback, include all relevant reactive values used by their callback in the dependency array. Follow the React Hooks lint rules to identify mistakes.
Rule 5: Use the Hooks Linter
The eslint-plugin-react-hooks package can help identify invalid Hook usage and missing dependencies.
15. Difference Between Class Components and Function Components with Hooks
| Feature |
Class Components |
Function Components with Hooks |
| Component definition |
Uses JavaScript class syntax. |
Uses a JavaScript function. |
| State management |
Commonly uses this.state and this.setState(). |
Uses Hooks such as useState or useReducer. |
| Lifecycle behavior |
Uses lifecycle methods such as componentDidMount. |
Often uses useEffect for external-system synchronization. |
| Accessing component values |
May use this. |
Uses variables and functions within the component. |
| Reusable stateful logic |
May use patterns such as higher-order components or render props. |
Can extract reusable logic into custom Hooks. |
| Modern development |
Still supported. |
Commonly preferred for new React components. |
Hooks do not remove or invalidate class components. Existing class components remain supported, and Hooks can be adopted gradually in function components.
16. Practical Project: Interactive Profile Card Using Hooks
This small project demonstrates how useState can manage profile information and a follow/unfollow button.
Project Requirements
- Display a user's name and role.
- Allow the user to change the displayed name.
- Toggle between Follow and Following.
- Update the interface when state changes.
Complete Code
import { useState } from "react";
function ProfileCard() {
const [name, setName] = useState("Alex");
const [isFollowing, setIsFollowing] = useState(false);
return (
<div>
<h2>User Profile</h2>
<p>Name: {name}</p>
<p>Role: React Learner</p>
<button onClick={() => setName("Jordan")}>
Change Name
</button>
<button onClick={() => setIsFollowing(value => !value)}>
{isFollowing ? "Following" : "Follow"}
</button>
</div>
);
}
export default ProfileCard;
Expected Output
- Initially, the profile name is Alex.
- Clicking Change Name changes the name to Jordan.
- Clicking Follow changes the button label to Following.
- Clicking Following changes the button label back to Follow.
What You Learn
This project demonstrates state initialization, event handling, functional state updates, conditional rendering, and re-rendering after a state change.
17. Common Mistakes When Using Hooks
| Mistake |
Correct Approach |
Calling useState inside an if statement. |
Call the Hook at the top level. |
| Calling a Hook from a click handler. |
Declare the Hook in the component and update state inside the handler. |
| Mutating an object in state directly. |
Create and set a new object or array instead. |
| Using an effect for every derived value. |
Calculate values during rendering when appropriate. |
| Leaving out necessary effect dependencies. |
Include relevant reactive values and follow lint guidance. |
Using useMemo and useCallback everywhere. |
Use memoization only when it provides a meaningful benefit. |
| Forgetting to clean up subscriptions or timers. |
Return a cleanup function from the effect when necessary. |
| Expecting a ref update to trigger rendering. |
Use state for values that need to update the rendered UI. |
18. Best Practices for React Hooks
- Use descriptive names for state variables and custom Hooks.
- Keep components focused on clear responsibilities.
- Use
useState for simple state and useReducer when state transitions become more complex.
- Use
useEffect to synchronize with external systems, not as a default way to calculate values.
- Clean up subscriptions, timers, and connections when needed.
- Keep dependency arrays accurate.
- Use functional state updates when the next value depends on the previous value.
- Use immutable updates for objects and arrays stored in state.
- Extract custom Hooks when behavior is genuinely reusable.
- Use React Developer Tools and the Hooks lint rules to help debug issues.
- Measure performance before adding memoization.
19. Interview Questions and Answers
Q1. What are React Hooks?
Answer: React Hooks are functions that let function components use React features such as state, effects, context, and references.
Q2. When were Hooks introduced?
Answer: Hooks were introduced in React 16.8.
Q3. What is useState?
Answer: useState adds a state variable to a function component and returns the current value and a setter function.
Q4. What is useEffect used for?
Answer: useEffect synchronizes a component with external systems, such as subscriptions, timers, and browser APIs.
Q5. What is the purpose of useContext?
Answer: useContext reads a value from React Context so components can access shared information without passing it through every intermediate component.
Q6. What is the difference between useState and useRef?
Answer: Updating state can trigger a re-render. Updating a ref's current property does not trigger a re-render by itself.
Q7. What is a custom Hook?
Answer: A custom Hook is a reusable JavaScript function that uses React Hooks to share behavior between components. Its name conventionally begins with use.
Q8. Can Hooks be called inside loops or conditions?
Answer: Ordinary Hooks such as useState and useEffect must not be called inside loops or conditions. They should be called at the top level of a function component or custom Hook. React's special use API has different rules.
Q9. What is useReducer?
Answer: useReducer manages state through a reducer function that calculates the next state from the current state and an action.
Q10. What is the difference between useMemo and useCallback?
Answer: useMemo caches a calculated value, while useCallback caches a function definition while its dependencies remain unchanged.
Q11. Do Hooks replace class components?
Answer: No. Hooks offer React features to function components, but class components remain supported.
Q12. Why is cleanup important in useEffect?
Answer: Cleanup removes resources created by an effect, such as event listeners, timers, and connections, helping prevent unwanted behavior and resource leaks.
20. Practice Exercises
- Create a counter with Increase, Decrease, and Reset buttons using
useState.
- Create a dark/light theme toggle using state.
- Build a form that stores a user's name and email using state.
- Use
useEffect to update the browser tab title when a counter changes.
- Create an input focus example using
useRef.
- Create a theme context and read it using
useContext.
- Build a counter with
useReducer.
- Create a custom Hook that tracks whether the browser is online.
- Filter a list of products and explore whether
useMemo is useful for the calculation.
- Review a component and identify any Hooks incorrectly placed inside conditions or event handlers.
21. Quick Revision
- React Hooks: Functions that provide React capabilities to function components.
- useState: Manages component state.
- useEffect: Synchronizes with external systems.
- useContext: Reads shared context values.
- useRef: Retains a value between renders without triggering a render when updated.
- useReducer: Manages state through actions and a reducer.
- useMemo: Caches the result of a calculation.
- useCallback: Caches a function definition.
- Custom Hooks: Reuse stateful logic across components.
- Rules of Hooks: Call ordinary Hooks at the top level of function components or custom Hooks.
22. Conclusion
React Hooks are fundamental to modern React development. They make it possible to manage component state, synchronize with external systems, access shared context, work with DOM references, and reuse logic through custom Hooks. Start by practicing useState and useEffect, then move on to useContext, useRef, useReducer, and performance-related Hooks as needed.
To continue learning React JS, explore the JustAcademy React JS Training course. You can also Register for React JS Course Demo to learn more about the training.
23. Official React Documentation