Description
When attempting to initialize a Redux store inside a Next.js (https://redux-toolkit.js.org/usage/nextjs#providing-the-store) using useRef to persist the store instance across renders, accessing storeRef.current during render results in error "Error: Cannot access refs during render"
Environment
"react-redux": "^9.2.0"
"react": "19.2.4",
"next": "16.2.4",
"@reduxjs/toolkit": "^2.11.2",
Code Example
'use client'
import { useRef } from 'react'
import { Provider } from 'react-redux'
import { makeStore, AppStore } from '../lib/store'
export default function StoreProvider({
children,
}: {
children: React.ReactNode
}) {
const storeRef = useRef<AppStore>(undefined)
// Error: Cannot access refs during render
if (!storeRef.current) {
// Create the store instance the first time this renders
storeRef.current = makeStore()
}
// Error: Cannot access refs during render
return <Provider store={storeRef.current}>{children}</Provider>
}
Description
When attempting to initialize a Redux store inside a Next.js (https://redux-toolkit.js.org/usage/nextjs#providing-the-store) using
useRefto persist the store instance across renders, accessingstoreRef.currentduring render results in error "Error: Cannot access refs during render"Environment
Code Example