#15 React JS Tutorial 2024
useReducer hook in React Js
In this tutorial, we will learn about the useReducer hook in React Js. The useReducer hook is a powerful alternative to useState that can be used to manage more complex state logic in a React application.
What is useReducer hook?
The useReducer hook is a built-in React hook that is used for managing state in a more complex way than the useState hook. It takes a reducer function as an argument and returns the current state and a dispatch function to update the state based on the action dispatched.
How to use useReducer hook in React Js?
Here is an example of how to use the useReducer hook in React Js:
import React, { useReducer } from 'react';
// Initial state
const initialState = { count: 0 };
// Reducer function
const reducer = (state, action) => {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
};
const App = () => {
const [state, dispatch] = useReducer(reducer, initialState);
return (
Count: {state.count}
);
};
export default App;
Conclusion
The useReducer hook in React Js is a powerful tool for managing complex state logic in a React application. It allows us to handle state updates in a more predictable and manageable way by using a reducer function. I hope this tutorial has helped you understand how to use the useReducer hook in React Js.
Thanks, very easily explained. 😄