react-store-js is a state management library for react based on svelte/store but adapted to the philosophy of react.
npm i react-store-jsto use react-state-js is very simple, just initialize your global state and then import it in your component, to mutate/update the state you can use the different hooks
example: counter.store.ts
import{createWritableStore}from"react-store-js";exportconstcounter=createWritableStore(0);on: App.tsx
import{useWritable}from"react-store-js";import{counter}from"./counter.store";exportdefaultfunctionApp(){const$counter=useWritable(counter);return(<div><buttononClick={()=>$counter.update(($counter)=>$counter+1)}>
count is {$counter.value}</button></div>);}Note: react-store-js is fully type-safe and typed, and generics can be used
createWritableStore(initialState, StartStopNotifier?): creates a state that can be fined and read
example:
exportconstcounter=createWritableStore(0);createReadableStore(initialState, StartStopNotifier?): creates a state that can only be read
example:
exportconstcounter=createReadableStore(0);getStore(state): gets the state directly, works with read-only states as well as mutable states
example:
exportconstcounter=createWritableStore(0);constvalue=getStore(couter);// return 0useWritable(state): can be used to mutate, update, and read state
example:
// initialize storeconstcounter=createWritableStore(0);// use storeconst$counter=useWritable(counter);// mutate the state directly$counter.set(0);// update the current state$counter.update(($counter)=>$counter+1);// get actual state$counter.value;useReadable(state): used to read the read-only state
example:
// initialize storeexportconstnow=createReadableStore(Date.now());const$now=useReadable(now);// get actual state$now.value;useDerived(state | state[], callback, initialState?): create a state whose value is based on the value of one or more other states
example:
// initialize storeconstcounter=createWritableStore(0);const$double=useDerived(counter,($couter)=>$counter*2,10);$double.value;useSubcriber(state, callback): used to listen for changes in state when the state changes
example:
constcounter=createWritableStore(0);const$counter=useWritable(counter);$counter.update(($counter)=>$counter+1);useEffect(()=>{constunsubcribe=useSubcriber(counter,($counter)=>{console.log($counter);// 1});// stop listening when component disconnectsreturnunsubcribe;},[]);createReadableStore with inside mutation:
on: time.store.ts
exportconsttime=createReadableStore(0,(set)=>{consta=setInterval(()=>set(Date.now()),1000);return()=>clearInterval(a);});createWritableStore with inside mutation:
on: time.store.ts
exportconsttime=createWritableStore(0,(set)=>{consta=setInterval(()=>set(Date.now()),1000);return()=>clearInterval(a);});