UseSelector Not Updating Even After Dispatch

Its quite possible that you are not able to update your component after dispatching and action.

There are some frequent possible causes for not updating

  • You are not dispatching action at all and only dispatching action function
  • You are not handling dispatched action in reducer correctly
  • Your selector function has wrong equalityFn/comparision function
  • You are not using selector function in right component

Dispatching action

// creating action
const increment = createAction('counter/increment');

// dispatcher
const dispatch = useDispatch();
dispatch(increment); // THIS IS WRONG

dispatch(increment()); // THIS IS RIGHT

make sure you are dispatching action by calling action creation funciton. you should not dispatch its function only.

Handle action correctly in reducer

const increment = createAction('counter/increment');

function counterReducer(state = initialState, action) {
  switch (action.type) {
    case 'increment': // <- NOT THIS
    case [increment]: // <- LIEK THIS - preffered way
    case 'counter/increment': // <- OR LIEK THIS
      return { ...state, value: state.value + 1 }
    default:
      return state
  }
}

make sure to type correct string of action in reducer function.

EqualityFn/comparision function

const counter = useSelector((state) => state.counter, () => {
    // some how this funciton is not returning false and not allowing 
    // to change value of counter
    return true;

    // both values means previous and new values
    // return true means both values are same do not change
    // return false means both values are different plz change
})

so make sure you are comparing values correctly and retuning correct boolean type to make updates.

Not using selector function in right component

const Demo = () => {
    const counter = useSelector((state) => state.counter));
    /// ...
}

if your state change are on state.products then this function will not update as it is only dependent on counter's value. so it will not update untill counter's value is not updated.

Mostly these are the main cause of UseSelector Not Updating component Even After Dispatch.

Related Articles

js interview questions