Simple state-management with React Context API
npm install state-context
state-context
does state management for React. In terms of complexity it is located between using local state and Redux.
- With
state-context
it's very easy to migrate your component from local state to global state:
Local state |
Global state with state-context
|
import * as React from 'react';
const MyBirthday: React.SFC = () => {
const [age, setAge] = React.useState(20);
return (
<button onClick={() => setAge(age + 1)}>
Celebrate {age} birthday!
</button>
);
}; |
import * as React from 'react';
import { MyStore } from './my-store';
const MyBirthday: React.SFC = () => {
const context = React.useContext(MyStore);
const [age, setAge] = context.useState.age;
return (
<button onClick={() => setAge(age + 1)}>
Celebrate {age} birthday!
</button>
);
}; |
- It's useful for cases where Redux boilerplate would be an overhead (it still makes sense and is easy to decouple state management from UI layer).
Redux | state-context |
|
actions.ts |
YES | NO |
actions.test.ts |
YES | NO |
reducer.ts |
YES | NO |
reducer.test.ts |
YES | NO |
side-effects.ts |
YES | NO |
side-effects.test.ts |
YES | NO |
container.tsx |
YES | YES |
container.test.tsx |
YES | YES |
ui-layer-component.tsx |
YES | YES |
ui-layer-component.test.tsx |
YES | YES |
- You can set up one global store or multiple shared-state containers.
- It's still deterministic as you can attach middleware and watch/undo/redo.
- You have TypeScript support out of the box.