0.0.23 • Published 5 years ago

restatable v0.0.23

Weekly downloads
1
License
MIT
Repository
github
Last release
5 years ago

restatable

npm

Simplify your global state in React

Why?

React state management is great, but as soon as you start dealing with global state, it can get messy. With Restatable, you can skip the ceremony around state management frameworks like Redux and keep using React like you always have; let Restatable take care of the rest.

Usage

Install using your favorite package manager

yarn add restatable

Create a Restatable store

import Restatable from 'restatable';

const theme = new Restatable({
  // set default state
  type: 'dark',
  highContrast: false,
});

export default theme;

Connect your stores to your component

import React, { PureComponent } from 'react';
import classNames from 'classnames';

import theme from '../restatables/theme';
import ContrastButton from '../components/ContrastButton';

class App extends PureComponent {
  constructor(props) {
    super(props);
    // connect your component
    theme.connect(this);
  }

  componentWillUnmount() {
    // disconnect when you're done
    theme.disconnect(this);
  }

  render() {
    // read state like normal
    const { type, highContrast } = this.state;

    return (
      <div className={classNames(type, highContrast && 'high-contrast')}>
        <ContrastButton />
      </div>
    );
  }
}

export default App;

Read this.state and use this.setState() like normal

import React, { PureComponent } from 'react';

import theme from '../restatables/theme';

class ContrastButton extends PureComponent {
  constructor(props) {
    super(props);
    theme.connect(
      this,
      // select only the keys you need
      ['highContrast'],
    );
  }

  componentWillUnmount() {
    theme.disconnect(this);
  }

  render() {
    const { highContrast } = this.state;

    return (
      <button
        onClick={() => {
          // and set state like normal
          this.setState(state => ({
            highContrast: !state.highContrast,
          }));
        }}
      >
        Turn high contrast {highContrast ? 'off' : 'on'}
      </button>
    );
  }
}

See the test cases for more in depth usage.

0.0.23

5 years ago

0.0.22

5 years ago

0.0.21

6 years ago

0.0.20

6 years ago

0.0.19

7 years ago

0.0.18

7 years ago

0.0.17

7 years ago

0.0.16

7 years ago

0.0.15

7 years ago

0.0.14

7 years ago

0.0.13

7 years ago

0.0.12

7 years ago

0.0.11

7 years ago

0.0.10

7 years ago

0.0.9

7 years ago

0.0.8

7 years ago

0.0.6

7 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago