Does RTK initialState update the components?

30 Views Asked by At

In Redux tool kit there is an option to set initial state. So we can create a reducer to set initial state.

My problem is, will it update all of the components which use that state?

import { createSlice } from '@reduxjs/toolkit'

const counterSlice = createSlice({
  name: 'counter',
  initialState: {name: 'stack'},
  reducers: {
      reset: () => initalState,
  },
})

I use name state in component A and then call reset reducer from component B. Even if the state is updated, component A will not re-render. Why is that? I wonder if this initialState function is not updating relevant content.

1

There are 1 best solutions below

1
Chinz On

Do ensure that the reducer is created the right way. In your given code, the reset reducer has not been created correctly.

Here is how you should do it:

const counterSlice = createSlice({
  name: 'counter',
  initialState: { name: 'stack' },
  reducers: {
    resetState: () => {
     const defaultState = { name: 'default' }
     return defaultState;
    }

Also, do ensure you are dispatching this correctly:

const ComponentB = () => {
  const name = useSelector(state => state.counter.name);

  const dispatch = useDispatch();

  const handleReset = () => {
    dispatch(resetState());
  };

  return (
    <div>
      <h1>Counter Name: {name}</h1>
      <button onClick={handleReset}>Reset Name</button>
    </div>
  );
};