React useReducer Hook


The useReducer Hook is similar to the useState Hook.

Allows a sense of custom status.

If you find yourself tracing many pieces of state that rely on complex intellectuals, the useReducer may be helpful.


Syntax

The use of Reducer Hook accepts two arguments.


useReducer (, )


reducer function contains your customization thinking and startup initialState may be simple but will usually contain something.

useReducer Hook restores current state and dispatch method.

Here is an example of a useReducer for a counter app:


Example
import { useReducer } from "react";
            import ReactDOM from "react-dom";
            
            const initialTodos = [
              {
                id: 1,
                title: "Todo 1",
                complete: false,
              },
              {
                id: 2,
                title: "Todo 2",
                complete: false,
              },
            ];
            
            const reducer = (state, action) => {
              switch (action.type) {
                case "COMPLETE":
                  return state.map((todo) => {
                    if (todo.id === action.id) {
                      return { ...todo, complete: !todo.complete };
                    } else {
                      return todo;
                    }
                  });
                default:
                  return state;
              }
            };
            
            function Todos() {
              const [todos, dispatch] = useReducer(reducer, initialTodos);
            
              const handleComplete = (todo) => {
                dispatch({ type: "COMPLETE", id: todo.id });
              };
            
              return (
                <>
                  {todos.map((todo) => (
                    <div key={todo.id}>
                      <label>
                        <input
                          type="checkbox"
                          checked={todo.complete}
                          onChange={() => handleComplete(todo)}
                        />
                        {todo.title}
                      </label>
                    </div>
                  ))}
                </>
              );
            }
            
ReactDOM.render(<Todos />, document.getElementById('root'));
            


This is just the tip of the iceberg.

All the wisdom of adding, removing, and completing tasks can be contained in one useReducer Hook by adding additional actions.