问题
We have a parent app which embed App.js and it will load it N times (in order to sync other embedded app)
Code 1, this is my 1st implementation. When App() is loaded N times, store will be created N times. We only want to the store to be created once, but can be loaded N times.
App.js
---
function App() {
const store = createReduxStore();
return (
<>
<StoreContext.Provider value={store}>
<Component />
</StoreContext.Provider>
</>
);
}
Code 2, store is a ref now, but correct me if wrong, <StoreContext.Provider value {store.current()}>. Store creation still happen N times?
App.js
---
function App() {
// lazy loaded
// https://reactjs.org/docs/hooks-reference.html#lazy-initial-state
const store = useRef(() => {
return createReduxStore();
});
return (
<>
<StoreContext.Provider value={store.current()}>
<Component />
</StoreContext.Provider>
</>
);
}
In summary, how to I make sure store creation happened only once, but can be loaded for N times?
回答1:
The comments in your second example mention lazy initial state, but that's a feature of useState
, not useRef
. So the code will set store.current
to be a function, and then every time App renders you have value={store.current()}
which is going to call that function and create a new redux store. So you end up with N stores anyway.
I would do one of the following.
Option 1: use a memo with an empty dependency array
const store = useMemo(() => {
return createReduxStore();
}, []);
Option 2: use a state with a lazy initializer, and never set the state
const [store] = useState(createReduxStore);
来源:https://stackoverflow.com/questions/64201022/how-to-make-sure-store-creation-happen-only-once-while-rendering-multiple-times