Simple React state management. Made with ❤️ and ES6 Proxies.
Simple React state management. Made with ❤️ and ES6 Proxies.
NEWS: v6.3.0 fixed a nasty bug that could render zombie children. Please update to this version at least to save yourself some headaches. Thanks!
Table of ContentsReact Easy State is a practical state management library with two functions and two accompanying rules.
view().store().import React from 'react';
import { store, view } from '@risingstack/react-easy-state';
const counter = store({
num: 0,
increment: () => counter.num++
});
export default view(() => (
<button onClick={counter.increment}>{counter.num}</button>
));This is enough for it to automatically update your views when needed. It doesn't matter how you structure or mutate your state stores, any syntactically valid code works.
Check this TodoMVC codesandbox or raw code for a more exciting example with nested data, arrays and getter properties.
npm install @risingstack/react-easy-state
Easy State supports Create React App without additional configuration. Just run the following commands to get started.
npx create-react-app my-app
cd my-app
npm install @risingstack/react-easy-state
npm startYou need npm 5.2+ to use npx.
store creates a state store from the passed object and returns it. A state store behaves just like the passed object. (To be precise, it is a transparent reactive proxy of the original object.)
import { store } from '@risingstack/react-easy-state';
const user = store({ name: 'Rick' });
// stores behave like normal JS objects
user.name = 'Bob';…import { store } from '@risingstack/react-easy-state';
const userStore = store({
user: {},
async fetchUser() {
userStore.user = await fetch('/user');
},
});
export default userStore;userStore.js
import { store } from '@risingstack/react-easy-state';
const userStore = store({
user: {},
async fetchUser() {
userStore.user = await fetch('/user');
},
});
export default userStore;recipesStore.js
import { store } from '@risingstack/react-easy-state';
import userStore from './userStore';
const recipesStore = store({
recipes: [],
async fetchRecipes() {
recipesStore.recipes = await fetch(
`/recipes?user=${userStore.user.id}`,
);
},
});
export default recipesStore;store as early as possible.
// DON'T DO THIS
const person = { name: 'Bob' };
person.name = 'Ann';
export default store(person);// DO THIS INSTEAD
const person = store({ name: 'Bob' });
person.name = 'Ann';
export default person;The first example wouldn't trigger re-renders on the person.name = 'Ann' mutation, because it is targeted at the raw object. Mutating the raw - none store-wrapped object - won't schedule renders.
this keyword in the methods of your state stores.
import { store, view } from '@risingstack/react-easy-state';
const counter = store({
num: 0,
increment() {
// DON'T DO THIS
this.num++;
// DO THIS INSTEAD
counter.num++;
},
});
export default view(() => (
));this.num++ won't work, because increment is passed as a callback and loses its this. You should use the direct object reference - counter - instead of this.
Wrapping your components with view turns them into reactive views. A reactive view re-renders whenever a piece of store - used inside its render - changes.
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';
// this is a global state store
const user = store({ name: 'Bob' });
// this is re-rendered whenever user.name changes
export default view(() => (
</div>
));view - including class and function ones - even if they don't seem to directly use a store.
Every component that is using a store or part of a store inside its render must be wrapped with view. Sometimes store usage is not so explicit and easy to to miss.
import { view, store } from '@risingstack/react-easy-state';
const appStore = store({
user: { name: 'Ann' },
});
const App = view(() => (
));
// DO THIS
const Profile = view(({ user }) => <p>Name: {user.name}</p>);
// DON'T DO THIS
// This won't re-render on appStore.user.name = 'newName' like mutations
const Profile = ({ user }) => <p>Name: {user.name}</p>;If you are 100% sure that your component is not using any stores you can skip the view wrapper.
import React from 'react';
// you don't have to wrap this component with `view`
export default (() => <p>This is just plain text</p>);view wrapping is advised even in these cases though.
view is pretty much equivalent to memo if you don't use any stores. That is nearly always nice to have.import React from 'react';
import { view, store } from '@risingstack/react-easy-state';
const user = store({ name: 'Bob' });
const timeline = store({ posts: ['react-easy-state'] });
// this is re-rendered whenever user.name or timeline.posts[0] changes
export default view(() => (
</div>
));view implements an optimal shouldComponentUpdate (or memo) for your components.
Using PureComponent or memo will provide no additional performance benefits.
Defining a custom shouldComponentUpdate may rarely provide performance benefits when you apply some use case specific heuristics inside it.
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';
const user = store({ name: 'Bob', age: 30 });
function mutateUser() {
user.name = 'Ann';
user.age = 32;
}
// calling `mutateUser` will only trigger a single re-render of the below component
// even though it mutates the store two times in quick succession
export default view(() => (
));If you mutate your stores multiple times synchronously from exotic task sources, multiple renders may rarely happen. If you experience performance issues you can batch changes manually with the batch function. batch(fn) executes the passed function immediately and batches any subsequent re-renders until the function execution finishes.
import React from 'react';
import { view, store, batch } from '@risingstack/react-easy-state';
const user = store({ name: 'Bob', age: 30 });
function mutateUser() {
// this makes sure the state changes will cause maximum one re-render,
// no matter where this function is getting invoked from
batch(() => {
user.name = 'Ann';
user.age = 32;
});
}
export default view(() => (
));Always applyNOTE: The React team plans to improve render batching in the future. The
batchfunction and built-in batching may be deprecated and removed in the future in favor of React's own batching.
view as the latest (innermost) wrapper when you combine it with other Higher Order Components.
import { view } from '@risingstack/react-easy-state';
import { withRouter } from 'react-router-dom';
import { withTheme } from 'styled-components';
const Comp = () =>
;
// DO THIS
withRouter(view(Comp));
withTheme(view(Comp));
// DON'T DO THIS
view(withRouter(Comp));
view(withTheme(Comp));If routing is not updated properly, wrap your view(Comp) - with the Routes inside - in withRouter(view(Comp)). This lets react-router know when to update.
The order of the HOCs matter, always use withRouter(view(Comp)).
This is not necessary if you use React Router 4.4+. You can find more details and some reasoning about this in this react-router docs page.
Usage with React Developer Tools.If you want React Developer Tools to recognize your reactive view components' names, you have to pass either a named function or an anonymous function with name inference to the view wrapper.
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';
const user = store({
name: 'Rick',
});
const componentName = () => (
);
export default view(componentName);Third party helpers - like data grids - may consist of many internal components which can not be wrapped by view, but sometimes you would like them to re-render when the passed data mutates. Traditional React components re-render when their props change by reference, so mutating the passed reactive data won't work in these cases. You can solve this i
No open issues yet, or sync has not completed.