Skip to main content

Command Palette

Search for a command to run...

useReducer in React

Published
2 min read
useReducer in React

State Management

In REACT state management is a vital part of the general architecture of a REACT app. The first and most powerful state management hook is the useState() hook. This is a very powerful hook and is ideal for tracking a state that does not have complex logic. However, when there is an application with a state that has more complex logic then the useReducer() hook is ideal for this kind of scenario.

Syntax

const [state, dispatch] = useReducer(reducer, initialState)

The reducer is the user-defined reducer function while the initialState is the pre-defined initial state of the application.

Use Case

Let’s start with a simple example of a log-in form that has the email and password. We are supposed to track the state using a reducer function. How can we go about this?

Step 1: Define the initial state and the reducer function

Initial state
const [state, dispatch] = useReducer(reducer, {email: "",passWord: ""});
Reducer Function

1

const reducer = (state, action) => {

Explanation

The reducer function is simply a switch statement that returns something if the test case is true. Here the test case is the type of a predefined action which is ‘handleMail’ and ‘handlePassword’. The …state tracks the previous state and the email and password update the state with a payload (action.payload). The payload is the new state that the user inputs. This ensures that state updates are always tracked.

Step 2: Define the form functions

1

const emailHandler = (e) => {

Explanation

The form functions that handle the email and the password have a dispatch that has an object with the action type and a payload. The type is used to access the action which is used inside the reducer function accessed as ‘action.type‘. The payload stores the form input which is later accessed in the reducer function as ‘action.payload‘.

Step 3:Create the form

1

<form>

Explanation

The form is a simple HTML form. The ‘value’ is the initial state defined in step 1 above. The state changes are tracked through the ‘onChange’ event listener.

Conclusion

The useReducer() hook is a simple and convenient way to update state and share data between our components in an organized way.

Updating the state only requires calling the dispatch(action) with the required action. The reducer() will update the forwarded state. Once the reducer updates the state it will re-render the component with the new state value.

A word of advice is that you should use the useState() hook for simple state management.

Happy coding

🙂