1 year ago

#358194

test-img

Aditi Sharma

conditionally update state in useReducer

I have written a reducer.

export const reducer = (state, { type, payload }) => {
  switch (type) {
    case ACTION_TYPES.UPDATE_STATE:
      return updateData({ state, payload });
    default:
      return state;
  }
};

const updateData = ({ state, payload }) => {
  const { key, value } = payload;
  const newState = {
    ...state,
    [key]: value,
  };
  const isEqual = JSON.stringify(newState) === JSON.stringify(state);
  if (!isEqual) {
    return newState;
  }
  return state;
};

I dont want to update the state when isEqual is true. But, the above code is updating the state as i can see the component is getting re rendered.

reactjs

react-hooks

use-reducer

0 Answers

Your Answer

Accepted video resources