0

Codesandbox: https://codesandbox.io/s/condescending-wiles-funk0?file=/src/App.js

Problem: When I update the state of my store the components are not re-rendered. In the above example you can see from the console that the data is correctly fetched, but the component is not re-rendered and keep rendering just Loading....

Expected behavior: When I update the state, the components are re-rendered.

I found a workaround by using useState in the component and subscribing to store changes like:

store.subscribe(() => setComponentState(store.getData())

This basically forces a re-render each time the data is updated.

I can mutate state: In the official docs they say that you can mutate the state since it has some magic that allows to do so (https://redux-toolkit.js.org/usage/usage-guide#simplifying-reducers-with-createreducer), hence that's not the issue.

Anyone has any idea about what's the appropriate way to make it work?

devamat
  • 1,529
  • 1
  • 15
  • 32

2 Answers2

1

From the useStore docs, it states that the hook shouldn't be used in an app because it doesn't cause the component to re-render:

// EXAMPLE ONLY! Do not do this in a real app.

// The component will not automatically update if the store state changes

Instead, you should be using useSelector instead.

On that note, how you have your codesandbox example would cause an infinite re-render since dispatch(fetchData()); is called every time the redux state is updated. Instead, you'll want to place it within React.useEffect.

For example, using useSelector with useEffect:

Edit Redux - useSelector

Matt Carlotta
  • 13,627
  • 3
  • 24
  • 39