useState vs useReducer, which one to use? and when?

useState vs useReducer, which one to use? and when?

Hello Everyone👋, useState and useReducer are react hooks use to manage states, if you have used useState hook and useReducer hook you must have thought of when to use which?. Let's together try to find out ans to it, let's goo... 🥳

useState

A very basic and mosted used hook useState hook is used to manage state's in React App, it is very easy to use, useState hook has a state itself and setter function using which you can preserve state in react component, if you didn't preserve your state, the state might be reinitialize with default value in case of re-rendering. In the below example you will see a useState returning a state by name stateName and it's setter function by name setStateName you can give the names as you want, the state has a default value of the "default state", you can give default of any type i.e, undefined, null, number, string, array, object, boolean etc.

import React, { useState } from "react";

function Eg1() {
  const [stateName, setStateName] = useState("default state");
  return <div>{stateName}</div>;
}

export default Eg1;

the above example we are not setting our state we are just accessing it, In below example we are setting our state with new values, here we have implemented a basic increment and decrement counter with a reset button, clicking "+" button the state is updated by one, the setter function has access to it's state, using which we can add one to it, same is happening when we click "-" button just rather than adding one in current state we are subtracting from current state, clicking on the "reset" button the counter is reset to zero.

import React, { useState } from "react";

function UseStateEg1() {
  const [count, setCount] = useState(0);
  return (
    <>
      <h2> Count Value : { count } </h2>
      <button onClick={() => setCount((count) => count + 1)}> + </button>
      <button onClick={() => setCount((count) => count - 1)}> - </button>
      <button onClick={() => setCount(0)}> Reset </button>
    </>
  );
}

export default UseStateEg1;

useReducer

useReducer Hook is also used to manage state in React App, useReducer is little different than useState and looking at useReducer you may will try to ignore it because it may happen you won't like it at first, but trust me you will start using it onces you start to understand it. So useReducer take two parameter, first is a reducer function and second is a initial state.

const [ state, dispatch ] = useReducer(reducerFn, initialState);

let's breakdown everything over here, in state we will get the current state which will be initialState in this case, think of dispatch as someone who will tell the reducerFn what action has to perform on state, the action could be increasing counter, decreasing counter or resetting it, and before you ask, reducerFn is a reducer function where our logic is written for every kind of action, and it is waiting for dispatch let him know what action has to be perform.

import React, { useReducer } from "react";

let intialState = 0;
const reducer = (state = intialState, action) => {
  switch (action.type) {
    case "increase":
      return state + 1;
    case "decrease":
      return  state - 1;
    case "reset":
      return action.payload;
    default:
      return state;
  }
};

function Eg1() {
  const [count, dispatch] = useReducer(reducer, intialState);
  return (
    <>
      <div> Count - {count} </div>
      <button onClick={() => dispatch({ type: 'increase' })}>increase</button>
      <button onClick={() => dispatch({ type : 'decrease' })}>Decrease</button>
      <button onClick={() => dispatch({ type : 'reset', payload : 0 })}>Reset</button>
    </>
  );
}

export default Eg1;

as I said earlier dispatch is used to tell reducerFn what action to perform on the state, so as you can see a dispatch method is passed with some kind of object which has property of "type" & "payload", type property tells reducerFn what type of action should be performed, for eg increase the counter can be denoted by type : 'increase' and to decrease the counter value we can say type : 'decrease', and write corresponding logic for it in the switch case, here you can see one more property payload, the payload is used to send data from the jsx to reducerFn function, you dont have to name the property payload you can name it anything you want, here we are resetting our state to 0 by passing value 0 as payload.

So as you have seen both of the hooks, lets take a guess together

1...

2...

3...

and the ans is ....

well it depends😅, their is no single word ans to it but their are cases in which senior devs suggest to use one over another and it may happen that you may not fully agree with them, but you are open to share your view in the comment section below.

Case 1 : Type of state you are trying to manage

If your type of state is Number, String, Boolean then it will be easy to you to manage it with useState, and if your type of state is something like array or object then using reducer hook may help you.

Case 2 : Number of state change

For less number of change's you should use the state hook, and for more number of state change you should use reducer hook has it will keep you code clean.

Case 3 : Complex

If your state is a complex one using reducer hook will help you manage it in a clean way, for less complex state alway use the state hook as you dont have to write alot of code.

Case 4 : Scope

Using the state hook your state can only be managed locally, using reducer hook you can manage your state globally with the help of useContext hook, you can also manage your state globally using useState but you will face a problem called prop drilling, because of which solutions like redux, and useContent are created.

So what do you think which one to use? and when?

Thank You for giving it a read🥳, I hope you liked it😁!

See you soon, Byee👋