Skip to content

mrac/state-context

Repository files navigation

state-context

Simple state-management with React Context API

Install

npm install state-context

Idea

state-context does state management for React. In terms of complexity it is located between using local state and Redux.

  1. 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>
  );
};

Plunker

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>
  );
};

Plunker

  1. 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
  1. You can set up one global store or multiple shared-state containers.
  2. It's still deterministic as you can attach middleware and watch/undo/redo.
  3. You have TypeScript support out of the box.

About

Simple state-management with React Context API

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published