useReducer hook explained React

useReducer hook explained React

·

4 min read

➜ The useReducer hook is similar to useState hook which is used to store the value and used later. useReducer is one of the new Hooks included with React 16.8. It is an alternative to the useState Hook that manages of complex state logic in React applications

➜ The useReducer Hook accepts two arguments. The reducer function contains your custom state logic and the initialState can be a simple value but generally will contain an object. The only job of a reducer is to Reduce! The useReducer Hook returns the current state and a dispatch method.

➜ The useReducer Hook is used to store and update states, just like the useState Hook. It accepts a reducer function as its first parameter and the initial state as the second.

➜ The Hooks that were introduced by React, two hooks serve as the functions for handling state objects and transitions: useState and useReducer.

➜ Reducers are pure functions that take in a state and action and return a new state. It's is just like a useState hook when store the state value and used when need. just the upgraded version of the useState hook.

➜⭐ Before going to useReducer hook, have the knowledge about how useState work it helps...

How to use useReducer hook

The useReducer hook takes three arguments including reducer, initial state, init.

const [state, dispatch] = useReducer(reducer, initialArgs, init);

✿ Lets breakdown the syntax and understand, How we define the useReducer hook what is in the syntax

★ state :→The state which is present in the component re-render cycle.
★ dispatch :→ dispatch is function which is used to update the state.

★ reducer :→ reducer function is the new state it performes when the action is dispatch, it receive the new state value where value should be updated.
★ intialArgs :→ The intial state function.
★ init :→ init is called "3d argument" lets you extract the logic for calculating the initial state outside the reducer.

Lets understand with the example

Just like the other React hooks, we have first import useReducer from react

import React, { usestate,useReducer } from 'react';

First create the simple increment, decrement function onClick() using useState. and we will see how to replace usestate to useReducer hook

First thing is to do is replace the state variable into useReducer function, set the count value to zero, userInput leave empty , color to false intially.

const [state, dispatch] = useReducer(reducer, { count: 0, userInput: '', color: false })

As we did in the useState, using onClick function increment , decrement add the countdown values

function App() 
const [state, dispatch] = useReducer(reducer, { count: 0, userInput: '', color: false })

  return (
    <main className="App" style={{ color: state.color ? '#FFF' : '#FFF952' }}>

      <section>
       <button onClick={reset}>reset</button>
       <button onClick={prev}>previous</button>
       <button onClick={next}>next</button>
      </section>

    </main>
  );
}

export default App;

Now add the input it should return when you type something when render the text printed down

     <input
        type="text"
        value={state.userInput}
        onChange={(e) => dispatch({ type: ACTION.NEW_USER_INPUT, payload: e.target.value })}
      /> 

       <p>{state.userInput}</p>

Now Added the reducer function which will be going to update the newstate using state and dispatch

const reducer = (state, action) => {
  switch (action.type) {
    case ACTION.INCREMENT:
      return { ...state, count: state.count + 1 };
    case ACTION.DECREMENT:
      return { ...state, count: state.count - 1 };
    case ACTION.NEW_USER_INPUT:
      return { ...state, userInput: action.payload };
    case ACTION.TG_COLOR:
      return { ...state, color: !state.color };
    default:
      throw new Error();
  }
}

Now define the action which should be performed on the reducer add the ACTION variable to dispatch the state value that should be updated

const ACTION = {
  INCREMENT: 'increment',
  DECREMENT: 'decrement',
  NEW_USER_INPUT: 'newUserInput',
  TG_COLOR: 'tgColor'
}

That's all defined reducer, added action and input text which will change color when click on it. the increment, decrement function dispatch const variable reducer function.

import { useState, useReducer } from 'react';
import React from 'react';

const ACTION = {
  INCREMENT: 'increment',
  DECREMENT: 'decrement',
  NEW_USER_INPUT: 'newUserInput',
  TG_COLOR: 'tgColor'
}

const reducer = (state, action) => {
  switch (action.type) {
    case ACTION.INCREMENT:
      return { ...state, count: state.count + 1 };
    case ACTION.DECREMENT:
      return { ...state, count: state.count - 1 };
    case ACTION.NEW_USER_INPUT:
      return { ...state, userInput: action.payload };
    case ACTION.TG_COLOR:
      return { ...state, color: !state.color };
    default:
      throw new Error();
  }
}

function App() {
  const [state, dispatch] = useReducer(reducer, { count: 0, userInput: '', color: false })

  return (
    <main className="App" style={{ color: state.color ? '#FFF' : '#FFF952' }}>
      <input
        type="text"
        value={state.userInput}
        onChange={(e) => dispatch({ type: ACTION.NEW_USER_INPUT, payload: e.target.value })}
      />

      <p>{state.count}</p>
      <section>
        <button onClick={(() => dispatch({ type: ACTION.DECREMENT }))}>-</button>
        <button onClick={(() => dispatch({ type: ACTION.INCREMENT }))}>+</button>
        <button onClick={(() => dispatch({ type: ACTION.TG_COLOR }))}>Color</button>
      </section>

      <p>{state.userInput}</p>
    </main>
  );
}

export default App;

It's done with useReducer hook .

Thank you Have a nice day ✿