State Management in React – Hooks, Context API and Redux
Last Updated :
28 Dec, 2023
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 techniques:
Before we dive deep into state management, let us first understand what is state in React.
What is state in React ?
React JS State is a way to store and manage the information or data while creating a React Application. The state is a JavaScript object that contains the real-time data or information on the webpage. The state in React is an instance of the React Component that can be defined as an object of a set of observable properties that control the behavior of the component. In other words, the State of a component is an object that holds some information that may change over the lifetime of the component.
Approach 1: Manage states using Hooks
Hooks were introduced in React 16.8, which makes a great revolution in functional components by helps them to manage state and lifecycle features.
useState is a fundamental hook by which we can easily able to manage states.It enables us to create and change state variables within our components, eliminating the need for class components.
Syntax:
const [state, setState] = useState(<default value>);
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.
Syntax:
const [state, dispatch] = useReducer(reducer, initialArgs, init);
Example: In this example we will see how we can manage state with the help of useState Hook.
JavaScript
import React, { useState } from 'react';
function App() {
const [click, setClick] = useState(0);
return (
<div>
<p>You've clicked {click} times!</p>
<p>The number of times you have clicked
is {click % 2 == 0 ? 'even!' : 'odd!'}</p>
<button onClick={() => setClick(click => click + 1)}>
Click me
</button>
</div>
);
}
export default App;