Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • React Tutorial
  • React Exercise
  • React Basic Concepts
  • React Components
  • React Props
  • React Hooks
  • React Router
  • React Advanced
  • React Examples
  • React Interview Questions
  • React Projects
  • Next.js Tutorial
  • React Bootstrap
  • React Material UI
  • React Ant Design
  • React Desktop
  • React Rebass
  • React Blueprint
  • JavaScript
  • Web Technology
Open In App
Next Article:
React Suite Notification Props & Hooks
Next article icon

Introduction to React Hooks

Last Updated : 28 Apr, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

  • ReactJs
  • React Components
  • React props
  • React lifecycle methods

Table of Content

  • What are React Hooks?
  • Why React Hooks?
  • Traditional way of managing state and side effects
  • Rules of React Hooks
  • Types of Hooks
  • Custom Hooks
  • Features of React Hooks

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:

count-incrementor-2


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:

lm-count

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.

useState :

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:

count-incrementor-2

useEffect :

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:

lm-count

useReducer :

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:

cdws

useLayoutEffect :

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:

cqa

useContext :

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 :

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 :

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

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 :

CustomHooks

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.

Next Article
React Suite Notification Props & Hooks

A

arikirevula_sanjay_praneeth
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • React-Hooks

Similar Reads

  • React Introduction
    ReactJS 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. It is developed and maintained by Facebook.The latest version of React is React 19.Use
    8 min read
  • State Hooks in React
    State Hooks, introduced in React 16.8, revolutionized how developers manage state in functional components. Before State Hooks, state management was primarily confined to class components using the setState method. State Hooks, such as useState, enable functional components to manage local state eff
    3 min read
  • Other Hooks in React
    React provides specialized built-in hooks for building reusable components and libraries. While they are used less, these hooks are important in providing library authors to create robust and user-friendly applications. Among these specialized hooks are useDebugValue and useId, that provides unique
    3 min read
  • Ref Hooks in React
    Ref Hooks provide a way to access and interact with the DOM (Document Object Model) nodes directly within functional components. Before hooks, refs were primarily used in class components. However, with Ref Hooks, functional components can also take advantage of this capability, enhancing flexibilit
    4 min read
  • React Suite Notification Props & Hooks
    React Suite is a popular front-end library with a set of React components that are designed for the middle platform and back-end products. Notification Component allows the user to display a notification message globally. The notification is also used with a toaster in react-based applications. <
    4 min read
  • Resource Hooks in React
    In React, components often need to access external resources such as data from promises or context information for styling. Managing these resources within the component state could lead to unnecessary complexity and performance overhead. React provides a simple solution with the 'use' hook to overc
    3 min read
  • Performance Hooks in React
    While developing React Applications, optimizing performance is one of the most important things for delivering a seamless user experience. One common way to boost performance is to minimize unnecessary re-renders by skipping repetitive calculations. React provides two powerful hooks, useMemo and use
    3 min read
  • New Hooks in React 18
    React's state, representing dynamic component data, is integral for effective component management. Initially confined to class components and managed using this.setState, the introduction of React Hooks in version 16.8 extended state usage to functional components. Hooks, functions enabling state a
    5 min read
  • React Hooks Tutorial
    React Hooks were introduced to solve some problems with class components in React. With Hooks, you can now add state, lifecycle methods, and other React features to functional components, which previously only class components could do. This makes development simpler because you can handle stateful
    3 min read
  • Built-in React Hooks
    In React, built-in Hooks are like tools that empower your components with various functionalities. They give you the flexibility to use different features without having to create class components. You can either utilize the hooks provided by React or mix and match them to create custom hooks tailor
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences