Skip to content

Easy to use Global State Manager for vanilla JS & React

Notifications You must be signed in to change notification settings

glitch-txs/cafe

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

63 Commits
 
 
 
 
 
 

Repository files navigation

Café

Café is a global state manager for React and vanilla JavaScript

React npm bundle size

npm i react-cafe

Create a store

// src/store/index.ts
import { createStore } from "react-cafe";

type MyStore = {
  count: number
}

export const myStore = createStore<MyStore>({
  count: 0
})

Use in any React Component

// src/components/Counter.tsx
import React from 'react'
import { myStore } from '../store'

const Counter = () => {

  const [count, setCount] = myStore.useCount()

  const increment = ()=>{
    setCount(p => p + 1)
  }

  return (
    <div>
      <button onClick={increment} >Increment</button>
      Count: {count}
    </div>
  )
}

export default Counter

Use outside React

// src/utils/vanilla.ts
import { myStore } from '../store'

const count = myStore.getCount() // Get a snapshot of the current value

myStore.setCount(p => p + 1) // Update state

Vanilla JS npm bundle size

npm i vanilla-cafe

Create a store

import { createStore } from "vanilla-cafe";

export const { set, sub, get } = createStore({
  count: 0
})

Update states

import { set, sub, get } from '../store';

function increment(){
  set.count(p => p + 1)
}

Subscribe to changes

let count = 0;

function handleCountChange(newValue){
  count = newValue
}

const unsubscribe = sub.count(handleCountChange)

Get the current state's value

const count = get.count()

About

Easy to use Global State Manager for vanilla JS & React

Resources

Stars

Watchers

Forks