create a reducer in javascript

A reducer in JavaScript is a function that receives two arguments: the current state and an action. It then returns the new state of the application by transforming the current state based on the provided action. Reducers are commonly used in state management libraries such as Redux for managing application state.

Here's an example of how to create a reducer function in JavaScript:

index.tsx
// Define an initial state for the reducer
const initialState = {
  username: '',
  email: '',
};

// Define a reducer function that takes in state and an action
function userReducer(state = initialState, action) {
  switch(action.type) {
    case 'UPDATE_USERNAME':
      // Return a new state with the updated username
      return {
        ...state,
        username: action.payload.username,
      };
    case 'UPDATE_EMAIL':
      // Return a new state with the updated email
      return {
        ...state,
        email: action.payload.email,
      };
    default:
      // If the action type is not known, return the current state
      return state;
  }
}
667 chars
27 lines

In this example, the reducer function takes in an initial state object and a switch statement that handles different action types. The reducer returns a new state object based on the action type and payload.

Reducers are typically used in a state management library such as Redux, where they are combined with other reducers to create the application state.

gistlibby LogSnag