Understanding the useReducer hook in React through a simple example

April 21, 2020 Goodman Loading... Post a comment

The useReducer hook is used for state management in React. When your app has complex state logic that involves multiple sub-values or when the next state depends on the previous one, you should use the useReducer hook instead of the useState hook.

The simple example below my help you understand the useReducer() hook better.

// Importing
import React, { useReducer } from "react";

// Creating the reducer function to update the state
const myReducer = (state, action) => {
  switch (action.type) {
    case "OLDER":
      return {
        ...state,
        age: state.age + 1,
      };
    case "YOUNGER":
      return {
        ...state,
        age: state.age - 1,
      };
    default:
      return state;
  }
};

// The initial state
const initialState = {
  name: "John Doe",
  age: 38,
}

// The App component
const App = () => {
  // Using the useReducer hook
  const [myState, myDispatch] = useReducer(myReducer, initialState);

  // Handling the button click events
  const btnClickHandler = type => {
    myDispatch({ type: type });
  };

  return (
    <div className="App">
      <h1>Age: {myState.age}</h1>
      <br />
      <button
        onClick={() => {
          btnClickHandler("OLDER");
        }}
      >
        Add One Year
      </button>

      <button
        onClick={() => {
          btnClickHandler("YOUNGER");
        }}
      >
        Subtract One Year
      </button>
    </div>
  );
};

export default App;

Execute your code:

Happy coding 🙂

guest
0 Comments
Inline Feedbacks
View all comments

Related Articles

0
Would love your thoughts, please comment.x
()
x