userreducer in react in javascript

In React, useReducer is a Hook that provides a way to share and manage state in functional components. It is an alternative to useState, and can be useful for managing more complex state changes.

Here's an example of how to use useReducer:

index.tsx
import React, { useReducer } from "react";

// Create a reducer function
const reducer = (state, action) => {
  switch (action.type) {
    case "INCREMENT":
      return { count: state.count + 1 };
    case "DECREMENT":
      return { count: state.count - 1 };
    default:
      throw new Error();
  }
};

// Set the initial state
const initialState = { count: 0 };

// Use the reducer in a component
const Counter = () => {
  const [state, dispatch] = useReducer(reducer, initialState);

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={() => dispatch({ type: "INCREMENT" })}>+</button>
      <button onClick={() => dispatch({ type: "DECREMENT" })}>-</button>
    </div>
  );
};
710 chars
30 lines

In this example, we create a reducer function that takes a state object and an action object, and returns a new state object based on the action type. We also set an initial state.

In the Counter component, we use useReducer to create a state object and a dispatch function. We pass in the reducer function and initial state as arguments to useReducer.

We render the current count from the state object, and provide buttons that dispatch actions to increment or decrement the count. These actions are handled in the reducer function.

Note that useReducer can also accept a third argument, which is a function to initialize the state. The third argument is useful when you need to compute the initial state based on props.

related categories

gistlibby LogSnag