What is the React useReducer hook?
The JavaScript user interface library React introduces hooks in version 16.8, giving developers a more compact and effective approach to managing state and side effects in functional components. useReducer is a powerful hook that may be used instead of useState to manage complex state logic in our components. React hook useReducer is used to handle the state in functional components. It is helpful when several sub-values exist, the state logic is complex, or the next state depends on the previous one.
With an emphasis on the useReducer hook as a particular use case, we will examine it in detail and its usefulness in this Answer.
The useReducer hook’s workflow
The useReducer hook in React follows a simple workflow:
Initialization: Provide an initial state and a reducer function to
useReducer.Dispatching Actions: Use the
dispatchfunction to send actions to the reducer.Reducer Execution: The reducer processes the current state and the dispatched action, returning a new state.
Component Rerender: The component rerenders with the updated state, reflecting changes in the UI.
Syntax
Let’s have a look at the syntax of the useReducer hook:
const [state, dispatch] = useReducer(reducer, initialState);
state: This variable reflects the current state of our component, managed by theuseReducerhook.dispatch: This is a function that dispatches actions to thereducerfunction. Upon the dispatch of an action, thereducerfunction is executed.reducer: It is a function that defines how the state should be updated. It accepts the current state and an action as arguments and returns the updated state based on the type of the action.initialState: This is the component’s initial state before any actions are dispatched.
Example
Run the code below to see useReducer hook in action:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<!--
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Explanation
Here’s the explanation of the code above:
Line 5-14:
stateandactionare the arguments of the reducer function, which, in our case, is named ascounterReducer, and inside this function, we’re usingswitchstatement to handle different types of actions which are dispatched by thedispatchfunction. This function increments or decrements thecountproperty of the state based on the providedactiontype. If theactiontype is unknown; then it throws an error.Line 19: The
initialCounterStateobject represents the initial state of the counter, and it has only a single propertycountinitialized to0.Line 22: Here, we’ve used
useReducerhook which takescounterReducerandinitialCounterStateas its arguments and returns an array of exactly two elements:The current state, which is named as
counterStatein this case.The
dispatchfunction, which dispatches an action to the reducer function, in this case, to thecounterReducer.
Line 28-33: The buttons have
onClickhandlers, that dispatch correspondingactiontypes to thecounterReducerfunction when clicked. And the component is rerendered accordingly.
This method may handle complex authentication and permission logic more easily, which offers a clean and maintainable solution to manage user-related states in a React application.
Wrap up
Conclusively, the React useReducer hook is an invaluable tool for handling state in functional components, particularly when working with complex state logic. The useReducer hook may be customized to handle user-related states tidily and effectively. React applications may be developed more easily and robustly by enclosing the user state and associated actions inside the reducer function. Thus resulting in a more manageable and modular code.
Free Resources