Introduction to React Hooks
Last Updated :
23 Jul, 2025
In React, Hooks are functions that allow you to manage state and perform side effects without the involvement of class components. Hooks were introduced in v16.8 of React and they can be accessed only through functional components but not through class components (Hooks were specifically designed for that). Hooks allow you to "hook into" React state and lifecycle features from functional components.
Prerequisites
What are React Hooks?
React Hooks are functions that allow you to use state and other React features without writing a class. Prior to Hooks, stateful logic in React components was primarily encapsulated in class components using the setState
method. Hooks provide a more functional approach to state management and enable the use of lifecycle methods, context, and other React features in functional components.
Note: React Hooks can't be used inside of class components.
Why React Hooks?
- Simplified Logic: Hooks eliminate the need for class components, reducing boilerplate code and making components easier to understand and maintain.
- Reusability: With Hooks, you can extract stateful logic into custom hooks and reuse it across multiple components, promoting code reuse and modularity.
- Improved Performance: Hooks optimize the rendering process by allowing React to memoize the state and only re-render components when necessary.
- Better Testing: Functional components with Hooks are easier to test compared to class components, as they are purely based on input and output.
Traditional way of managing state and side effects
Managing state variable's value through class components traditionally, Now, let us implement an incrementor that increments the number by clicking a button.
Example: Implementation to show managing state and side effects.
JavaScript
import React, { Component } from 'react'
export default class Incrementor extends Component {
constructor(){
super();
this.state={
count:0
};
}
increment = ()=>{
this.setState({
count: this.state.count + 1
});
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.increment}>
increment
</button>
</div>
)
}
}
Output:

Managing side effects through a class component traditionally, Side effects these are the operations that are performed to fetch data or to manipulate DOM are known as side effects.Now, let us perform a side effect by changing the title of the document after every increment of the count value.
Example: Implementation to show side effects with an example.
JavaScript
import React, { Component } from 'react'
export default class Incrementor extends Component {
constructor() {
super();
this.state = {
count: 0
};
}
incrementor = () => {
this.setState({
count: this.state.count + 1
});
}
componentDidUpdate() {
document.title =
`Count incremented to ${this.state.count}`;
}
render() {
return (
<div>
<h1>{this.state.count}</h1>
<button onClick={this.incrementor}>
increment
</button>
</div>
)
}
}
Output:

Rules of React Hooks
- Hooks should be called only at the top level.
- Don't call hooks conditonally and inside a loop.
- Hooks should be called only in a functional component but not through regular JavaScript functions.
Types of Hooks
State Hook allows us to manage component state directly within functional components, without the necessity of class components. State in React refers to any data or property that is dynamic and can change overtime.
It manages state in functional components by providing a state variable and a function to update it, enabling dynamic UI updates.
Syntax :
const [stateVariable, setStateFunction] = useState(initialStateValue)
Example: Implementation to the use show the use of usestate hook.
JavaScript
import React from 'react'
import {useState} from 'react';
export default function Incrementor() {
const [count,setCount]=useState(0);
const increment=()=>{
setCount(count+1);
}
return (
<>
<h1>{count}</h1>
<button onClick={increment}>increment</button>
</>
)
}
Output:

It handles side effects like data fetching, subscriptions, or DOM manipulation in functional components after rendering.
Syntax:
useEffect(() => {
// Effect code
return () => {
// Cleanup code
};
}, [dependencies]);
Example:
JavaScript
import React from "react";
import { useState, useEffect } from "react";
export default function Incrementor() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count incremented to ${count}`;
});
const increment = () => {
setCount(count + 1);
};
return (
<>
<h1>{count}</h1>
<button onClick={increment}>increment</button>
</>
);
}
Output:

useReducer
is a Hook in React used for state management. It accepts a reducer function and an initial state, returning the current state and a dispatch function. The dispatch function is used to trigger state updates by passing an action object to the reducer. This pattern is especially useful for managing complex state logic and interactions in functional components.
Syntax:
const [state, dispatch] = useReducer(reducer, initialState);
Example :
JavaScript
import React, { useReducer } from "react";
function reducer(state, action) {
switch (action) {
case "add":
return state + 1;
case "subtract":
return state - 1;
default:
throw new Error("Unexpected action");
}
};
function MyComponent() {
const [count, dispatch] = useReducer(reducer, 0);
return (
<>
<h2>{count}</h2>
<button onClick={() => dispatch("add")}>
add
</button>
<button onClick={() => dispatch("subtract")}>
subtract
</button>
</>
);
};
export default MyComponent;
Output:

useLayoutEffect
is a Hook in React similar to useEffect
, but it synchronously runs after all DOM mutations. It's useful for operations that need to be performed after the browser has finished painting but before the user sees the updates.
Note : It is recommended to use "useEffect" over "useLayoutEffect" whenever possible , because "useLayoutEffect" effects the performance of the application.
Example :
JavaScript
import React from "react";
import { useState, useLayoutEffect } from "react";
export default function MyComponent() {
const [count, setCount] = useState(0);
const increment = () => {
setCount(count + 1);
};
useLayoutEffect(() => {
console.log("Count is Incremented");
}, [count]);
return (
<>
<h1>{count}</h1>
<button onClick={increment}>
Increment
</button>
</>
);
}
Output:

useContext
simplifies data sharing by allowing components to access context values without manual prop drilling. It enables passing data or state through the component tree effortlessly.
Syntax:
const value = useContext(MyContext);
useCallback
memoizes callback functions, preventing unnecessary re-renders of child components when the callback reference remains unchanged. It optimizes performance by avoiding the recreation of callbacks on each render.
Syntax:
const memoizedCallback = useCallback(() => {
// Callback logic
}, [dependencies]);
useMemo
memoizes function values, preventing unnecessary re-renders due to changes in other state variables. It's used to optimize performance by memoizing expensive calculations or derived values.
Syntax:
const memoizedValue = useMemo(() => {
// Value computation logic
}, [dependencies]);
Custom Hooks in React allows you to create your own hook and helps you to reuse that hook's functionality across various functional components. A custom hook can be created by naming a JavaScript function with the prefix "use".
Note : If the JavaScript function is not named with the prefix "use", React considers it as a regular JavaScript function.
Syntax :
function useCustomHook() {
//code to be executed
}
Example : Implementation to show the use the sue of custom hooks.
JavaScript
//useCustomHook.js
import { useState} from "react";
export function useCustomHook(value) {
const [count,setCount]=useState(value);
const increment = () => {
setCount(count + 1);
};
return{
count,
increment,
};
};
JavaScript
// FirstComponent.js
import {useCustomHook} from "./useCustomHook";
export default function FirstComponent(){
const {count,increment} = useCustomHook(0);
return (
<>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
</>
);
};
JavaScript
// SecondComponent.js
import {useCustomHook} from "./useCustomHook";
export default function SecondComponent(){
const {count,increment} = useCustomHook(0);
return (
<>
<h1>{count}</h1>
<button onClick={increment}>Increment</button>
</>
);
};
Output :

Features of React Hooks
- Functional Components: Allow using state and lifecycle methods in functional components without needing class syntax.
- Reusability: Promote reusability of stateful logic by encapsulating it in custom hooks.
- Simplified Lifecycle: Offer useEffect hook for handling side effects, replacing componentDidMount, componentDidUpdate, and componentWillUnmount.
- Clean Code: Reduce boilerplate and improve readability by removing class components and HOCs.
- Improved Performance: Optimize rendering performance by memoizing values with useMemo and callbacks with useCallback.
- Easier Testing: Simplify unit testing of components with hooks by decoupling logic from the UI.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
8 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
6 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects