How to make sure store creation happen only once while rendering multiple times by parent?

北慕城南 提交于 2021-02-11 12:19:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!