Skip to content

Instantly share code, notes, and snippets.

@lanqy
Forked from gaearon/index.js
Created August 27, 2016 04:09
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lanqy/190d47962d2a8e3eacd0876d60cb8160 to your computer and use it in GitHub Desktop.
Breaking out of Redux paradigm to isolate apps
import React, { Component } from 'react'
import Subapp from './subapp/Root'
class BigApp extends Component {
render() {
return (
<div>
<Subapp />
<Subapp />
<Subapp />
</div>
)
}
}
// These subapps will be completely independent.
//
// They won't share data or actions, and won't see or communicate with each other.
// If you mix this approach with standard Redux approach of composing reducers, it
// will get extremely confusing so it's best if you pick just one: either your app
// is composed of pieces that follow Redux pattern holistically, or your app is so
// large and disjointed that smaller independent "subapps" make more sense.
//
// The first case is probably closer to normal web products, and the second case is
// closer to a "product hub", a "dashboard", or enterprise software where unrelated
// tools are grouped together because they're part of one package.
// This is our subapp's root connected component.
// It can render more components, connected or not, below, just like normally.
// Usually we'd render it in <Provider> and be done with it.
class App extends Component { ... }
export default connect(mapStateToProps)(App)
// However we don't have to call ReactDOM.render(<Provider><App /></Provider>)
// if we're interested in hiding the fact that it's a Redux app.
//
// Maybe we want to be able to run multiple instances of it in the same "bigger" app
// and keep it as a complete black box, with Redux being an implementation detail.
// To hide Redux behind a React API, we can wrap it in a special component that
// initializes the store in the constructor. This way every instance will be independent.
//
// Note that this is *not* recommended for parts of the same app that share data.
// But it can be useful when the bigger app has zero access to smaller apps' internals,
// and we'd like to keep the fact that they are implemented with Redux an implementation detail.
// Each component instance will have its own store, so they won't "know" about each other.
import React, { Component } from 'react'
import { Provider } from 'react-redux'
import reducer from './reducers'
import App from './App'
class Root extends Component {
constructor(props) {
super(props)
this.store = createStore(reducer)
}
render() {
return (
<Provider store={this.store}>
<App />
</Provider>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment