I am using useContext for global state management with useReducer.I am using WebSocket to retrieve bitcoin data every second.Because of the data changing frequently, I am getting my app re-rendered every second and I have heavy data calculations, complex UI with tables and etc.Even though not any component is a consumer for bitcoin data, anyway every component is being re-rendered every time it's data is changed.
this is the context provider.
const AppContext = createContext<{
state: InitialStateType;
dispatch: Dispatch<ActionType>;
}>({
state: initialState,
dispatch: () => null,
});
const mainReducer: MainReducer = ({btc, common, user }, action) => ({
btc: btcReducer<BTCPayload>(btc, action as BTCReducerActions),
user: userReducer<UserPayload>(user, action as UserReducerActions),
common: commonReducer<CommonPayload>(common, action as CommonReducerActions),
});
const AppProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(mainReducer, initialState);
return (
<AppContext.Provider value={{ state, dispatch }}>
{children}
</AppContext.Provider>
);
};
export { AppProvider, AppContext };
And here is the wrapper for the app.
<AppProvider>
<ThemeProvider theme={theme}>
<GlobalStyles />
<BrowserRouter>
<div className="App">
<AppRoot isBusy={!ready || !isConnected} />
</div>
</BrowserRouter>
</ThemeProvider>
</AppProvider>
I have tried to create separate providers one for the btc data, and the another one for the rest of the data, but it's working the same, because I guess the reason is that the whole app is inside that context provider.
const AppProvider: React.FC = ({ children }) => {
const [state, dispatch] = useReducer(mainReducer, initialState);
const appValue = useMemo(() => {
return { state, dispatch };
}, [state]);
const btcValue = useMemo(() => {
return { btc };
}, [btc]);
return (
<AppContext.Provider value={appValue}>
<BtcContext.Provider value={btcValue}>
{children}
</BtcContext.Provider>
</AppContext.Provider>
);
};
I am struggling almost 2 days.I need to wrap the whole app with the provider because there are more than 10 components using btc data in different routes.