reduxjs / redux

A JS library for predictable global state management
https://redux.js.org
MIT License
60.51k stars 15.26k forks source link

Should not set the useRef current value during rendering #4690

Closed raRaRa closed 1 month ago

raRaRa commented 1 month ago

What docs page needs to be fixed?

What is the problem?

The suggested way of storing the store in a useRef does not follow the guidelines from React. That is, we are not supposed to set the value of current during rendering.

Do not write or read ref.current during rendering.

Here's the piece of code from the documentation:

const storeRef = useRef<AppStore | null>(null)
if (!storeRef.current) {
  storeRef.current = makeStore()
  storeRef.current.dispatch(initializeCount(count))
}

What should be changed to fix the problem?

Not quite sure. I managed to create the store outside the component just fine with NextJS client component. Unsure what side-effects that will have. But it seems to work just fine since nothing in the store is SSR or RSC.

EskiMojo14 commented 1 month ago

The documentation you're quoting says

Do not write or read ref.current during rendering, except for initialization.

if you read the section on initialization, that's exactly what we're doing here.

phryneas commented 1 month ago

Also, definitely do not create a store for usage in Next.js outside of a component. Your components will SSR and this can have all kinds of weird consequences.