3.0.0-pre.1 • Published 4 years ago

@gitbook/unstated v3.0.0-pre.1

Weekly downloads
7
License
MIT
Repository
github
Last release
4 years ago

@gitbook/unstated

Simple state library for react application. It is based on unstated by James Kyle.

Installation

$ yarn add @gitbook/unstated

Usage

import { Container, useUnstated } from '@gitbook/unstated';

class Counter extends Container<{
    count: number
}> {
    state = {
        count: 0
    };

    increment() {
        this.setState({ count: this.state.count + 1 });
    }

    decrement() {
        this.setState({ count: this.state.count - 1 });
    }
}

function Counter() {
    const counter = useUnstated(Counter);

    return (
        <div>
            <button onClick={() => counter.decrement()}>-</button>
            <span>{counter.state.count}</span>
            <button onClick={() => counter.increment()}>+</button>
        </div>
    );
}

render(
    <Provider>
        <Counter />
    </Provider>,
    document.getElementById('root')
);

API

useUnstated

import { useUnstated } from '@gitbook/unstated';

useUnstated(
    C: ContainerConstructor,
    shouldUpdate?: (C: Container) => any
): Container

Hook to access a container and update the compontent each time the state is updated.

The shouldUpdate function can be used to prevent update of your component for certain updates of state. The result of the function will be shallowly compare to previous result.

useContainer

import { useContainer } from '@gitbook/unstated';

useContainer(
    C: ContainerConstructor
): Container

Similar to useUnstated but the component is not updated when the state is updated. You can use this hook to access actions to modify the container.

Credits

This module is based on unstated. It started as a fork to add support for hooks.

3.0.0-pre.1

4 years ago

2.0.3

5 years ago

2.0.2

5 years ago

2.0.1

5 years ago

2.0.0

5 years ago

1.0.1

5 years ago

1.0.0

5 years ago