Frontend Scrapbook

Notes that make a difference

Access Redux store external to react ecosystem

By admin

on Tue Jun 09 2020

I recently happen to see a code written by an experienced developer.

global.reduxState = store

global is like ‘window’, but in NodeJS env. By default, all the variables, functions declared has local scope in a Node module. If you consider all the files are imported within a container namespace, global points to exactly the same, where you can declare variables common to all.

This was done in order to access the store from utilities which are ‘outside’ the react ecosystem. This is a classic example of ‘abuse’ of the env.

Remember, our utilities needs to be independent. Shouldn’t access store directly whenever possible. Utilities needs to be part of redux flow, where you can pass data from the store to utility function. In cases, where you have no absolute way, but needs to access the store, export it separately in a separate module.

One of the possible approach may be as follows.

Have store created in a separate file as below ( say, store.js )

import rootReducer from './reducer';
import middlewares from './middleware';

const store = createStore(rootReducer, middlewares);
export default store;

The above approach will help us to import the store wherever required in a clean way.

Any thoughts ?. Let’s have a conversation below.