Skip to content

Instantly share code, notes, and snippets.

@jonidelv
Last active March 29, 2019 07:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonidelv/86322a5df0cf370aa5b5f546a8b3bf5d to your computer and use it in GitHub Desktop.
Save jonidelv/86322a5df0cf370aa5b5f546a8b3bf5d to your computer and use it in GitHub Desktop.
Redux Store

Redux Store

Best way to create the Redux store if we want to consume it from any JS file


When creating the store in a React-redux app there are differents ways to doit, here is the simple one that allow you to consume the sotre from anywhere. What I mean by that is be able to see the store, dispatch actions and even suscribe to changes from any JS file outside React.

Creating the Store

What I like to do is having two diferent store files, one for Production, other for Development. Then an Index file (inside the store folder) that will export the store depending on the env. (dev or prod)

store/
  index.js
  storeDev.js
  storeProd.js

You can see what is inside each Store file here: I made a yeoman generator that have this an another goodies -> storeDev.js storeProd.js This is the index file that export each store

const { default: store } = process.env.NODE_ENV === 'production'
  ? require('./storeProd')
  : require('./storeDev')

module.exports = store()

Importing and consuming the Store

First import the store and pass it to the Provider to make the Redux app work.

import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import store from './store'
import App from './App'

render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root'),
)

Then from any JS File

import store from './store'

const state = store.getState()
const dispatch = store.dispatch

Example here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment