Skip to content

Latest commit

 

History

History
104 lines (74 loc) · 2.57 KB

README.md

File metadata and controls

104 lines (74 loc) · 2.57 KB

Venti

Global State for React

Build Status

Install

npm i venti

Quick Start

Get global state

import React from 'react'
import { useVenti } from 'venti'

export default function Book({ id }) {
  const state = useVenti()
  const { author, title } = state.get(`books.${id}`, {})
  const year = state.get(`books.${id}.year`)
  return <div>"{title}" by {author} ({year})</div>
}

Set global state

import { state } from 'venti'

state.set('books.1', {
  author: 'John Steinbeck',
  title: 'Cannery Row',
  year: 1945
})

API

useVenti( [state] )

  • state {State} (optional) defaults to singleton state if not provided
  • Returns state that has been instrumented to update the component when applicable
  • See StateEventer for more info

state.get( path, [defaultValue] )

  • path {Array|string} The path to get
  • defaultValue {*} (optional) The value returned for undefined resolved values
  • Returns the resolved value

state.set( path, value )

  • path {Array|string} The path of the property to set
  • value {*} The value to set

state.unset( path )

  • path {Array|string} The path of the property to unset

state.update( path, transformFn, [defaultValue] )

  • path {Array|string} The path of the property to set
  • transformFn {Function} transforms the current value to a new value
  • defaultValue {*} (optional) the default value to pass into the transform function if the existing value at the given path is undefined
    state.update('counter', n => n + 1, 0)

Advanced Usage

If you don't want to use Venti's singleton state, you can do this:

import React from 'react'
import { State, useVenti } from 'venti'

const globalState = new State()
const useGlobalState = () => useVenti(globalState)

export default function Book({ id }) {
  const state = useGlobalState()
  const { title, year } = state.get(`books.${id}`)
  return <div>{title} ({year})</div>
}

Performance Benchmarks

Color Matrix Benchmark

Examples

Tests

npm test

License

MIT