Open In App

State Hooks in React

Last Updated : 20 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 effortlessly, aligning with React’s philosophy of simplicity and composability.

  • useState hook is used to declare state variable in functional components
  • useReducer hook is used when state management becomes difficult with useState Hook

There are different state hooks we will learn about them:

Table of Content

useState Hook:

useState() hook allows one to declare a state variable inside a function. It should be noted that one use of useState() can only be used to declare one state variable. It was introduced in version 16.8.

Syntax:

const [var, setVar] = useState(0);

Internal working of useState hook:

useState() maintains state by updating a stack within the functional component’s object in memory. Each render creates a new stack cell for the state variable. The stack pointer tracks the latest value for subsequent renders. Upon user-initiated refresh, the stack is cleared, triggering a fresh allocation for the component’s rendering.

Example: Below is the code example of useState Hook:

Javascript




import React, { useState } from 'react';
 
function App() {
    const [click, setClick] = useState(0);
    return (
        <div>
            <p>You clicked {click} times</p>
            <button onClick={() => setClick(click + 1)}>
                Click me
            </button>
        </div>
    );
}
 
export default App;


Steps to run the App:

npm start

Output:

useReducer Hook:

The useReducer Hook is the better alternative to the useState hook and is generally more preferred over the useState hook when you have complex state-building logic or when the next state value depends upon its previous value or when the components are needed to be optimized.

The useReducer hook takes three arguments including reducer, initial state, and the function to load the initial state lazily.

Syntax:

const [state, dispatch] = useReducer(reducer, initialArgs, init);

Example: Here reducer is the user-defined function that pairs the current state with the dispatch method to handle the state, initialArgs refers to the initial arguments and init is the function to initialize the state lazily.

Javascript




import React,
{
    useReducer
} from "react";
 
// Defining the initial state and the reducer
const initialState = 0;
const reducer = (state, action) => {
    switch (action) {
        case "add":
            return state + 1;
        case "subtract":
            return state - 1;
        case "reset":
            return 0;
        default:
            throw new Error("Unexpected action");
    }
};
 
const App = () => {
    // Initialising useReducer hook
    const [count, dispatch] =
        useReducer(reducer, initialState);
    return (
        <div>
            <h2>{count}</h2>
            <button onClick={() => dispatch("add")}>
                add
            </button>
            <button onClick={() => dispatch("subtract")}>
                subtract
            </button>
            <button onClick={() => dispatch("reset")}>
                reset
            </button>
        </div>
    );
};
 
export default App;


Steps to run the App:

npm start

Output:



Similar Reads

When is it best to use custom hooks instead of built-in React hooks?
Custom hooks in React are useful when you want to extract and reuse stateful logic across multiple components. While built-in React hooks like useState, useEffect, and useContext cover many common scenarios, there are cases where creating custom hooks can enhance code organization, readability, and reusability. When to Choose for Custom Hooks in Re
2 min read
How to set an object key inside a state object in React Hooks?
We can update a React hooks state object that has a nested object containing objects with index keys with the following approach, Before doing so, consider the following example: Example: Following is the default state object: const [data, setData] = useState({ name:'', contact:'', address:{ 0:{}, 1:{}, } }) Following is the desired output after up
2 min read
State Management in React – Hooks, Context API and Redux
While developing a React Application, it is very important to manage the state efficiently for building fully functional applications. As React is growing there are multiple approaches introduced that can help to manage state efficiently depending upon the type of application we are building. We will discuss the following state management technique
6 min read
Create a Quiz App using React Hooks and Timer-Based State Management
Quiz Application is a web-based application built using React Hooks and Timer-Based State Management. It provides users with a series of multiple-choice questions and requires them to select an option within a given time limit. If the user fails to select an option within the specified time, the application automatically moves to the next question.
5 min read
Explain the new feature of React hooks introduced in React v16.8
React v16.8 is no less than a miracle for all the React developers because this version of React introduced hooks to all of us. Before its release, the developer community was tired of using class components but they still had to use them because the functional component does not provide many features that the class component provides. But after ho
7 min read
Why to use React Hooks Instead of Classes in React JS ?
The introduction of React Hooks has changed the way we are managing states and lifecycle features. They offer more easy and functional way as compared to class based components. In this article, we will learn why to use React Hooks Instead of Classes in ReactJS, but lets first discuss about both React hooks and class based components. Table of Cont
4 min read
What are React Hooks, and why were they added to React?
React Hooks are a way to add functionality to functional components in React. Before Hooks, functional components were more limited compared to class components in terms of what they could do. With Hooks, users can now use state, lifecycle methods, and other React features in functional components, making them more powerful and flexible. Hooks Addr
2 min read
What are the React Router hooks in React v5?
React Router hooks perform client-side single-page routing that provides a functional and streamlined approach to managing navigation in React applications. It provides a way to directly access the state of the router from functional components, this simplifies tasks like retrieving information about the desired URL and navigating through web pages
5 min read
How to use componentWillMount() in React Hooks?
The componentWillMount() method allows us to execute the React code synchronously when the component gets loaded or mounted in the DOM (Document Object Model). This method is called during the mounting phase of the React Life-cycle. You cannot use any of the existing React lifecycle methods like ComponentDidMount, ComponentWillUnmount, etc. in a ho
2 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. &lt;Notification&gt; Props: closable: It is a boolean
4 min read