Hooks in react js ( useReducer hooks )

Hooks in react js ( useReducer hooks )

For small task useState is the best but for big task useReducer is recommended.

import React, {useEffect, useReducer, useState} from "react";

const reducerFun = (state, action) => {
    if(action.type === "INCR"){
        state = state + 1;
    }
    if(state > 0 && action.type === "DECR"){
        state = state - 1;
    }
    return state;
}

let UseReducer = () => {
    let intialData = 10;
    const [state, dispatch] = useReducer(reducerFun, intialData);
    // dispatch will work for trigger reducerFun

    useEffect(() => {
        document.title = `Chats(${state})`;
    });  

    return (
        <>
           <center>
            <h1>{state}</h1>
            <buttononClick={() =>dispatch({type:"INCR"})}>Increase +</button>&nbsp;&nbsp;
            <button onClick={() => dispatch({type:"DECR"})}>Reduce -</button>
           </center>
        </>
    )
}

export default UseReducer;

Leave a Reply