Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/solkimicreb/react-easy-state
Simple React state management. Made with ❤️ and ES6 Proxies.
https://github.com/solkimicreb/react-easy-state
es6-proxies javascript react react-state reactive-programming reactjs state state-management
Last synced: 3 months ago
JSON representation
Simple React state management. Made with ❤️ and ES6 Proxies.
- Host: GitHub
- URL: https://github.com/solkimicreb/react-easy-state
- Owner: RisingStack
- License: mit
- Created: 2017-05-23T15:17:43.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T21:00:43.000Z (almost 2 years ago)
- Last Synced: 2024-04-17T01:49:47.301Z (7 months ago)
- Topics: es6-proxies, javascript, react, react-state, reactive-programming, reactjs, state, state-management
- Language: JavaScript
- Homepage:
- Size: 17.5 MB
- Stars: 2,559
- Watchers: 42
- Forks: 104
- Open Issues: 199
-
Metadata Files:
- Readme: README.md
- Contributing: CONTRIBUTING.md
- License: LICENSE
Awesome Lists containing this project
- awesome - react-easy-state - Simple React state management. Made with ❤️ and ES6 Proxies. (JavaScript)
- awesome-react-state-management - react-easy-state - Minimal React state management with the power of ES6 Proxies (List)
- awesome-star-libs - solkimicreb / react-easy-state
README
## React Easy State - by [RisingStack](https://risingstack.com/)
[![Build](https://img.shields.io/circleci/project/github/RisingStack/react-easy-state/master.svg)](https://circleci.com/gh/RisingStack/react-easy-state/tree/master) [![dependencies Status](https://david-dm.org/RisingStack/react-easy-state/status.svg)](https://david-dm.org/RisingStack/react-easy-state) [![Coverage Status](https://coveralls.io/repos/github/RisingStack/react-easy-state/badge.svg?branch=master&service=github)](https://coveralls.io/github/RisingStack/react-easy-state?branch=master) [![Package size](https://img.shields.io/bundlephobia/minzip/@risingstack/react-easy-state.svg)](https://bundlephobia.com/result?p=@risingstack/react-easy-state) [![Version](https://img.shields.io/npm/v/@risingstack/react-easy-state.svg)](https://www.npmjs.com/package/@risingstack/react-easy-state) [![License](https://img.shields.io/npm/l/@risingstack/react-easy-state.svg)](https://www.npmjs.com/package/@risingstack/react-easy-state)
[![All Contributors](https://img.shields.io/badge/all_contributors-4-blue.svg)](#contributors)**NEWS:** v6.3.0 fixed a nasty bug that could render [zombie children](https://react-redux.js.org/api/hooks#stale-props-and-zombie-children). Please update to this version at least to save yourself some headaches. Thanks!
Table of Contents
* [Introduction :wave:](#introduction-wave)
* [Installation :cd:](#installation-cd)
* [Everyday Usage :sunglasses:](#everyday-usage-sunglasses)
+ [Creating global stores](#creating-global-stores)
+ [Creating reactive views](#creating-reactive-views)
+ [Creating local stores](#creating-local-stores)
* [Advanced Usage :nerd_face:](#advanced-usage-nerd_face)
+ [Adding side effects](#adding-side-effects)
* [API Summary :book:](#api-summary-book)
+ [store(obj)](#storeobj)
+ [view(Comp)](#viewcomp)
+ [batch(fn)](#batchfn)
+ [autoEffect(fn)](#autoeffectfn)
+ [clearEffect(fn)](#cleareffectfn)
* [Examples with live demos :tv:](#examples-with-live-demos-tv)
* [Articles :loudspeaker:](#articles-loudspeaker)
* [Performance :rocket:](#performance-rocket)
* [Platform support :computer:](#platform-support-computer)
* [Alternative builds :wrench:](#alternative-builds-wrench)
* [Contributors :sparkles:](#contributors-sparkles)## Introduction :wave:
React Easy State is a practical state management library with two functions and two accompanying rules.
1. Always wrap your components with `view()`.
2. Always wrap your state store objects with `store()`.```jsx
import React from 'react';
import { store, view } from '@risingstack/react-easy-state';const counter = store({
num: 0,
increment: () => counter.num++
});export default view(() => (
{counter.num}
));
```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](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/todo-mvc?module=%2Fsrc%2FtodosStore.js) or [raw code](/examples/todo-mvc/src/todosStore.js) for a more exciting example with nested data, arrays and getter properties.
## Installation :cd:
`npm install @risingstack/react-easy-state`
Setting up a quick project
Easy State supports Create React App without additional configuration. Just run the following commands to get started.
```sh
npx create-react-app my-app
cd my-app
npm install @risingstack/react-easy-state
npm start
```_You need npm 5.2+ to use npx._
## Everyday Usage :sunglasses:
### Creating global stores
`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.)
```js
import { store } from '@risingstack/react-easy-state';const user = store({ name: 'Rick' });
// stores behave like normal JS objects
user.name = 'Bob';
```State stores may have arbitrary structure and they may be mutated in any syntactically valid way.
```js
import { store } from '@risingstack/react-easy-state';// stores can include any valid JS structure
// including nested data, arrays, Maps, Sets, getters, setters, inheritance, ...
const user = store({
profile: {
firstName: 'Bob',
lastName: 'Smith',
get name() {
return `${user.profile.firstName} ${user.profile.lastName}`;
},
},
hobbies: ['programming', 'sports'],
friends: new Map(),
});// stores may be mutated in any syntactically valid way
user.profile.firstName = 'Bob';
delete user.profile.lastName;
user.hobbies.push('reading');
user.friends.set('id', otherUser);
```Async operations can be expressed with the standard async/await syntax.
```js
import { store } from '@risingstack/react-easy-state';const userStore = store({
user: {},
async fetchUser() {
userStore.user = await fetch('/user');
},
});export default userStore;
```State stores may import and use other state stores in their methods.
_userStore.js_
```js
import { store } from '@risingstack/react-easy-state';const userStore = store({
user: {},
async fetchUser() {
userStore.user = await fetch('/user');
},
});export default userStore;
```_recipesStore.js_
```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;
```Wrap your state stores with
store
as early as possible.```js
// DON'T DO THIS
const person = { name: 'Bob' };
person.name = 'Ann';export default store(person);
``````js
// 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.
Avoid using the
this
keyword in the methods of your state stores.```jsx
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(() => (
{counter.num}
));
````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`.
### Creating reactive views
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.
```jsx
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(() => (
(user.name = ev.target.value)}
/>
Hello {user.name}!
));
```Wrap ALL of your components with
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.
```jsx
import { view, store } from '@risingstack/react-easy-state';const appStore = store({
user: { name: 'Ann' },
});const App = view(() => (
My App
));// DO THIS
const Profile = view(({ user }) =>Name: {user.name}
);// DON'T DO THIS
// This won't re-render on appStore.user.name = 'newName' like mutations
const Profile = ({ user }) =>Name: {user.name}
;
```If you are **100% sure** that your component is not using any stores you can skip the `view` wrapper.
```jsx
import React from 'react';// you don't have to wrap this component with `view`
export default (() =>This is just plain text
);
````view` wrapping is advised even in these cases though.
- It saves you from future headaches as your project grows and you start to use stores inside these components.
- `view` is pretty much equivalent to `memo` if you don't use any stores. That is nearly always nice to have.A single reactive component may use multiple stores inside its render.
```jsx
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(() => (
Hello {user.name}!
Your first post is: {timeline.posts[0]}
));
```
view
implements an optimalshouldComponentUpdate
(ormemo
) 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.
Reactive renders are batched. Multiple synchronous store mutations won't result in multiple re-renders of the same component.
```jsx
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(() => (
name: {user.name}, age: {user.age}
));
```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.
```jsx
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(() => (
name: {user.name}, age: {user.age}
));
```> **NOTE:** The React team plans to improve render batching in the future. The `batch` function and built-in batching may be deprecated and removed in the future in favor of React's own batching.
Always apply
view
as the latest (innermost) wrapper when you combine it with other Higher Order Components.```jsx
import { view } from '@risingstack/react-easy-state';
import { withRouter } from 'react-router-dom';
import { withTheme } from 'styled-components';const Comp = () =>
A reactive component;// DO THIS
withRouter(view(Comp));
withTheme(view(Comp));// DON'T DO THIS
view(withRouter(Comp));
view(withTheme(Comp));
```Usage with (pre v4.4) React Router.
- If routing is not updated properly, wrap your `view(Comp)` - with the `Route`s 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](https://github.com/ReactTraining/react-router/blob/master/packages/react-router/docs/guides/blocked-updates.md).
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.
```jsx
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';const user = store({
name: 'Rick',
});const componentName = () => (
{user.name}
);export default view(componentName);
```Passing nested data to third party components.
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 issue by deep cloning the observable data before passing it to the component. This creates a new reference for the consuming component on every store mutation.
```jsx
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';
import Table from 'rc-table';
import cloneDeep from 'lodash/cloneDeep';const dataStore = store({
items: [
{
product: 'Car',
value: 12,
},
],
});export default view(() => (
));
```### Creating local stores
A singleton global store is perfect for something like the current user, but sometimes having local component states is a better fit. Just create a store inside a function component or as a class component property in these cases.
#### Local stores in function components
```jsx
import React from 'react'
import { view, store } from '@risingstack/react-easy-state'export default view(() => {
const counter = store({ num: 0 })
const increment = () => counter.num++
return {counter.num}
})
```**Local stores in functions rely on React hooks. They require React and React DOM v16.8+ or React Native v0.59+ to work.**
You can use React hooks - including
useState
- in function components, Easy State won't interfere with them. Consider using autoEffect instead of theuseEffect
hook for the best experience though.```jsx
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';export default view(() => {
const [name, setName] = useState('Ann');
const user = store({ age: 30 });
return (
setName(ev.target.value)} />
(user.age = ev.target.value)}
/>
);
});
```#### Local stores in class components
```jsx
import React, { Component } from 'react';
import { view, store } from '@risingstack/react-easy-state';class Counter extends Component {
counter = store({ num: 0 });
increment = () => counter.num++;render() {
return (
{this.counter.num}
);
}
}export default view(Counter);
```You can also use vanilla
setState
in your class components, Easy State won't interfere with it.```jsx
import React, { Component } from 'react';
import { view, store } from '@risingstack/react-easy-state';class Profile extends Component {
state = { name: 'Ann' };
user = store({ age: 30 });setName = ev => this.setState({ name: ev.target.value });
setAge = ev => (this.user.age = ev.target.value);render() {
return (
);
}
}export default view(Profile);
```Don't name local stores as
state
. It may conflict with linter rules, which guard against direct state mutations.```jsx
import React, { Component } from 'react';
import { view, store } from '@risingstack/react-easy-state';class Profile extends Component {
// DON'T DO THIS
state = store({});
// DO THIS
user = store({});
render() {}
}
```Deriving local stores from props (
getDerivedStateFromProps
).Class components wrapped with `view` have an extra static `deriveStoresFromProps` lifecycle method, which works similarly to the vanilla `getDerivedStateFromProps`.
```jsx
import React, { Component } from 'react';
import { view, store } from '@risingstack/react-easy-state';class NameCard extends Component {
userStore = store({ name: 'Bob' });static deriveStoresFromProps(props, userStore) {
userStore.name = props.name || userStore.name;
}render() {
return{this.userStore.name};
}
}export default view(NameCard);
```Instead of returning an object, you should directly mutate the received stores. If you have multiple local stores on a single component, they are all passed as arguments - in their definition order - after the first props argument.
## Advanced Usage :nerd_face:
### Adding side effects
Use `autoEffect` to react with automatic side effect to your store changes. Auto effects should contain end-of-chain logic - like changing the document title or saving data to LocalStorage. `view` is a special auto effect that does rendering.
Never use auto effects to derive data from other data. Use dynamic getters instead.
```jsx
import { store, autoEffect } from '@risingstack/react-easy-state';// DON'T DO THIS
const store1 = store({ name: 'Store 1' })
const store2 = store({ name: 'Store 2' })
autoEffect(() => store2.name = store1.name)// DO THIS INSTEAD
const store1 = store({ name: 'Store 1' })
const store2 = store({ get name () { return store1.name } })
```#### Global auto effects
Global auto effects can be created with `autoEffect` and cleared up with `clearEffect`.
```jsx
import { store, autoEffect, clearEffect } from '@risingstack/react-easy-state';const app = store({ name: 'My App' })
const effect = autoEffect(() => document.title = app.name)// this also updates the document title
app.name = 'My Awesome App'clearEffect(effect)
// this won't update the document title, the effect is cleared
app.name = 'My App'
```#### Local auto effects in function components
Use local auto effects in function components instead of the `useEffect` hook when reactive stores are used inside them. These local effects are automatically cleared when the component unmounts.
```jsx
import React from 'react'
import { store, view, autoEffect } from '@risingstack/react-easy-state';export default view(() => {
const app = store({ name: 'My App' })
// no need to clear the effect
autoEffect(() => document.title = app.name)
})
```Explicitly pass none reactive dependencies - like vanillas props and state - to local auto effects in function components.
Because of the design of React hooks you have to explicitly pass all none reactive data to a hook-like dependency array. This makes sure that the effect also runs when the none reactive data changes.
```jsx
import React from 'react'
import { store, view, autoEffect } from '@risingstack/react-easy-state';export default view(({ greeting }) => {
const app = store({ name: 'My App' })
// pass `greeting` in the dependency array because it is not coming from a store
autoEffect(() => document.title = `${greeting} ${app.name}`, [greeting])
})
```#### Local auto effects in class components
Local effects in class components must be cleared when the component unmounts.
```jsx
import React, { Component } from 'react'
import { store, view, autoEffect } from '@risingstack/react-easy-state';class App extends Component {
app = store({ name: 'My App' })componentDidMount () {
this.effect = autoEffect(() => document.title = this.app.name)
}componentWillUnmount () {
// local effects in class components must be cleared on unmount
clearEffect(this.effect)
}
}
```## API Summary :book:
### store(obj)
Creates an observable store from the passed object and returns it. Can be used outside components for [global stores](#creating-global-stores) and inside components for [local stores]((#creating-local-stores)).
```js
import { store } from '@risingstack/react-easy-state';const user = store({ name: 'Rick' });
```### view(Comp)
Creates a [reactive view](#creating-reactive-views) from the passed component and returns it. A reactive view re-renders whenever any store data used inside it is mutated.
```jsx
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';const user = store({ name: 'Bob' });
export default view(() => (
Hello {user.name}!
));
```### batch(fn)
Immediately executes the passed function and batches all store mutations inside it. Batched mutations are guaranteed to not trigger unnecessary double renders. Most task sources are batched automatically, only use `batch` if you encounter performance issues.
```jsx
import React from 'react';
import { view, store } from '@risingstack/react-easy-state';const user = store({ name: 'Bob' });
function setName() {
batch(() => {
user.name = 'Rick'
user.name = 'Ann'
})
}
```### autoEffect(fn)
Creates a reactive function from the passed one, immediately executes it, and returns it. A reactive function automatically re-reruns whenever any store data used inside it is mutated.
Can be used both [outside](#global-auto-effects) and [inside](#local-auto-effects-in-function-components) components.
```js
import { store, autoEffect } from '@risingstack/react-easy-state';const user = store({ name: 'Bob' })
autoEffect(() => document.title = user.name)
```### clearEffect(fn)
Takes a reactive function (returned by `autoEffect`) and clears the reactivity from it. Cleared reactive functions will no longer re-rerun on related store mutations. Reactive functions created inside function components are automatically cleared when the component unmounts.
```js
import { store, autoEffect, clearEffect } from '@risingstack/react-easy-state';const user = store({ name: 'Bob' })
const effect = autoEffect(() => document.title = user.name)
clearEffect(effect)
```## Examples with live demos :tv:
#### Beginner
- [Clock Widget](https://risingstack.github.io/react-easy-state/examples/clock/build) ([source](/examples/clock/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/clock)) ([react-native source](/examples/native-clock/)) ([react-native sandbox](https://snack.expo.io/@git/github.com/RisingStack/react-easy-state:examples/native-clock)): a reusable clock widget with a tiny local state store.
- [Stopwatch](https://risingstack.github.io/react-easy-state/examples/stop-watch/build) ([source](/examples/stop-watch/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/stop-watch)) ([tutorial](https://hackernoon.com/introducing-react-easy-state-1210a156fa16)): a stopwatch with a mix of normal and getter state properties.#### Advanced
- [Pokédex](https://risingstack.github.io/react-easy-state/examples/pokedex/build) ([source](/examples/pokedex/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/pokedex)): a Pokédex app build with Apollo GraphQL, async actions and a global state.
- [TodoMVC](https://risingstack.github.io/react-easy-state/examples/todo-mvc/build) ([source](/examples/todo-mvc/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/todo-mvc)): a classic TodoMVC implementation with a lot of getters/setters and implicit reactivity.
- [Contacts Table](https://risingstack.github.io/react-easy-state/examples/contacts/build) ([source](/examples/contacts/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/contacts)): a data grid implementation with a mix of global and local state.
- [Beer Finder](https://risingstack.github.io/react-easy-state/examples/beer-finder/build) ([source](/examples/beer-finder/)) ([codesandbox](https://codesandbox.io/s/github/RisingStack/react-easy-state/tree/master/examples/beer-finder)) ([tutorial](https://medium.com/@solkimicreb/design-patterns-with-react-easy-state-830b927acc7c)): an app with async actions and a mix of local and global state, which finds matching beers for your meal.## Articles :loudspeaker:
- [Introducing React Easy State](https://blog.risingstack.com/introducing-react-easy-state/): making a simple stopwatch.
- [Stress Testing React Easy State](https://medium.com/@solkimicreb/stress-testing-react-easy-state-ac321fa3becf): demonstrating Easy State's reactivity with increasingly exotic state mutations.
- [Design Patterns with React Easy State](https://medium.com/@solkimicreb/design-patterns-with-react-easy-state-830b927acc7c): demonstrating async actions and local and global state management through a beer finder app.
- [The Ideas Behind React Easy State](https://medium.com/dailyjs/the-ideas-behind-react-easy-state-901d70e4d03e): a deep dive under the hood of Easy State.## Performance :rocket:
You can compare Easy State with plain React and other state management libraries with the below benchmarks. It performs a bit better than MobX and similarly to Redux.
- [js-framework-benchmark](https://github.com/krausest/js-framework-benchmark) ([source](https://github.com/krausest/js-framework-benchmark/tree/master/react-v16.1.0-easy-state-v4.0.1-keyed)) ([results](https://rawgit.com/krausest/js-framework-benchmark/master/webdriver-ts-results/table.html))
## Platform support :computer:
- Node: 6 and above
- Chrome: 49 and above
- Firefox: 38 and above
- Safari: 10 and above
- Edge: 12 and above
- Opera: 36 and above
- React Native: 0.59 and above_This library is based on non polyfillable ES6 Proxies. Because of this, it will never support IE._
## Alternative builds :wrench:
This library detects if you use ES6 or commonJS modules and serve the right format to you. The default bundles use ES6 features, which may not yet be supported by some minifier tools. If you experience issues during the build process, you can switch to one of the ES5 builds from below.
- `@risingstack/react-easy-state/dist/es.es6.js` exposes an ES6 build with ES6 modules.
- `@risingstack/react-easy-state/dist/es.es5.js` exposes an ES5 build with ES6 modules.
- `@risingstack/react-easy-state/dist/cjs.es6.js` exposes an ES6 build with commonJS modules.
- `@risingstack/react-easy-state/dist/cjs.es5.js` exposes an ES5 build with commonJS modules.If you use a bundler, set up an alias for `@risingstack/react-easy-state` to point to your desired build. You can learn how to do it with webpack [here](https://webpack.js.org/configuration/resolve/#resolve-alias) and with rollup [here](https://github.com/rollup/rollup-plugin-alias#usage).
## Contributors :sparkles:
Contributions are always welcome, please read our [contributing documentation](CONTRIBUTING.md).
Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
Miklos Bertalan
💻 ⚠️ 📖 📝
Roland
💻 ⚠️ 📖
Daniel Gergely
💻 🎨 💡
Peter Czibik
🚇
This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome!