Introduction to useReducer in React.js

Introduction to useReducer in React.js

React.js provides the useReducer hook for managing state in a more complex and efficient manner. While useState is suitable for simple state management, useReducer is ideal when dealing with intricate state updates or large state objects.

Understanding the useReducer Hook

The useReducer hook takes a reducer function and an initial state value as arguments. The reducer function evaluates dispatched actions and returns a new state based on the action type.

Example of useReducer

import React, { useReducer } from 'react';


const initialState = { count: 0 };


function reducer(state, action) {
  switch (action.type) {
    case 'INCREMENT':
      return { count: state.count + 1 };
    case 'DECREMENT':
      return { count: state.count - 1 };
    case 'SET_COUNT':
      return { count: action.payload };
    default:
      throw new Error();
  }
}


function Counter() {
  const [state, dispatch] = useReducer(reducer, initialState);


  const setCount = (newCount) => {
    dispatch({ type: 'SET_COUNT', payload: newCount });
  };


  return (
    <div>
      <h2>Count: {state.count}</h2>
      <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
      <button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
      <button onClick={() => setCount(10)}>Set Count to 10</button>
    </div>
  );
}


export default Counter;        

In this example, we have a counter component that enables users to increment or decrement a counter value. To manage the state of the counter, we use the useReducer hook.

Conclusion

The useReducer hook in React.js is a powerful tool for managing state in complex scenarios. By using a reducer function, state updates become predictable and efficient. While we explored a simple counter example, you can apply the useReducer hook to various advanced use cases in your React applications.

Moula Ali Syed

Principal Consultant at Nexer Group

1y

Add an example with Payload as well.

Like
Reply

To view or add a comment, sign in

More articles by Ramdhas M

Insights from the community

Others also viewed

Explore topics