![]() |
VOOZH | about |
State management is a critical concept when working with React. React components can hold local state, but as applications grow, managing state across multiple components can become complex. To help manage this complexity, React provides several tools: Hooks, Context API, and Redux.
Here are some features of State Management:
React Hooks were introduced in version 16.8 and provide a way to manage state and lifecycle methods in functional components. Before hooks, class components were used for managing state, but now, functional components with hooks have become the standard for most React apps.
The useState Hook is the most commonly used hook for local state management in functional components. It allows a component to have its state that can be modified using a setter function.
Syntax
const [state, setState] = useState(<default value>);In the above syntax
Now let's understand this with the help of an example
In this example
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 need to be optimized.
Syntax:
const [state, dispatch] = useReducer(reducer, initialArgs, init);The Context API is a feature built into React that allows for global state management. It is useful when we need to share state across many components without having to pass props down through multiple levels of the component tree.
Syntax
const authContext = useContext(initialValue);Now let's understand this with the help of example:
Output
In this example
For more details follow this article => ReactJS useContext Hook
Redux is a state managing library used in JavaScript apps. It simply manages the state of your application or in other words, it is used to manage the data of the application. It is used with a library like React. It makes easier to manage state and data. As the complexity of our application increases.
Now let's understand this with the help of example
Install dependency to use Redux in your application
npm install redux react-reduxOutput
In this example
For more details follow this article => Introduction to React-Redux
Below are the comparison between the state management hooks:
Hooks | Context API | Redux |
|---|---|---|
Local state management in a component | Shared state across many components | Centralized state management in large apps |
Simple and easy to use | Simple but can become complex with large apps | More complex but powerful |
Optimized for local state | Good for medium-sized apps, can cause performance issues in large apps | Optimized for large apps with middleware |
Single component state | Passing data across deep component trees | Large-scale apps with many components needing to share state |
Inside the component | Global but only for specific contexts | Global store accessible from any component |