React UnStated — Aggregation of state between different state containers

Amit Dhaka
JustFrontendThings
Published in
2 min readApr 5, 2018

I recently started using react unstated. I took help of this quick start guide. It took me a couple of readings to understand the wiring of unstated containers to React components and how to use it effectively to manage the state of a component. I put it to practical use in a personal project. If you are new to React or React-unstated, refer the guide below before proceeding further.

https://medium.com/react-native-training/unstated-the-setstate-of-react-state-management-8ce47b240e6d

React Unstated was a breeze to use and it simplified my components by pulling out all the state related logic into unstated containers. But soon, I realized changing state of one unstated container from another container was not straightforward.

I had kept auth state and database interactions in separate containers and wanted to make a database read call as soon as user auth was successful. To overcome this, I set a flag in auth state and made a check in my React Component to make the database read. But, I realized by making these checks I’ll end up writing state logic in my React components.

Aggregation was a problem for me now. After giving some thought, I realized that Unstated provides a way to inject the container objects. Using inject approach, I added a bind method to the container which can be used to influence the state of the component we bind with.

Here’s an example:

import { Provider, Subscribe } from 'unstated';
import AuthContainer from './state/AuthContainer';
import DBContainer from './state/DBContainer';
// AuthContainer is written belowconst authContainer = new AuthContainer();
const dbContainer = new DBContainer();
// aggregation of state
authContainer.bindDB(dbContainer);
export default class App extends Component {
render() {
return (
<Provider inject={[authContainer, dbContainer]}>
<Subscribe to={[AuthContainer, DBContainer]}>
{ (auth, db) => {
return ( *Render your application*);
}}}
</Subscribe>
</Provider>
);
}
}

I used bindDb to bind DbContainer to AuthContainer. Now, we can call the database read from AuthContainer upon successful authentication.

Here is how →

import { Container } from 'unstated';export default class AuthContainer extends Container { 
authenticate() {
// call onAuthSuccess on successful authentication
}
onAuthSuccess() {
// database read calls
this.db.getAllThings();
}
bindDb(db) {
this.db = db;
}
}

That’s all for now. I’ll be writing a follow-up article if there is any new pattern that I come across. Please share your feedback in the comments and share your views if you’ve used it.

--

--

Amit Dhaka
JustFrontendThings

Javascript > Web Developer > Software Engineer. Working at Directi.