mistate
v1.2.2
Published
[![npm](https://img.shields.io/npm/v/mistate.svg)](https://www.npmjs.com/package/mistate) ![gzip size](https://img.shields.io/badge/gzip%20size-910%20B-44cc11.svg) [![Build Status](https://travis-ci.org/forsigner/mistate.svg?branch=master)](https://travis
Downloads
12
Readme
Mistate
The smallest state management library for React
Less than 1kb after gzip, 40 lines code only, one Api only.
Installation
yarn add mistate
Usage
import React from 'react'
import { render } from 'react-dom'
import { create } from 'mistate'
const { get, set } = create({ text: 'foo' })
const App = () => (
<div>
<span>{get(s => s.text)}</span>
<button onClick={() => set({ text: 'bar' })}>set</button>
<button onClick={() => set({ text: 'foo' })}>reset</button>
</div>
)
render(<App />, document.getElementById('root'))
Check on CodeSandbox: example
Examples
API
Only one Api:
get()
Get state in Component, Component will re-render if state is setted;
First, you need create a store, example:
const { get, set } = create({ text: 'foo' })
Simple usage
<span>{get(s => s.text)}</span>
Using selectors
<div>
{get(
s => s.text,
text => (
<span>{text}</span>
),
)}
</div>
set()
Update state use set()
in it, you can call it in anywhere, in React lifecycle fn、stateless componet... even out of React component, so you don't need HOC.
Set with object
set({ text: 'bar' })
Set with function
set(s => ({ text: s.text + 'bar' }))
Return a Promise
async function setText() {
const newState = await set({ text: 'bar' })
// { text: 'bar' }
}
getState()
Get the current state object.
const { getState } = create({ text: 'foo' })
const currentState = getState()