DEV Community

Rivier Grullon
Rivier Grullon

Posted on

Introducing react-store-js: A State Management Library Tailored for React inspire in Svelte store

As developers in the ever-evolving landscape of web development, we are constantly seeking efficient tools that seamlessly integrate with our preferred frameworks. One such tool that caters to the React community is react-store-js – a state management library inspired by svelte/store but designed with the React philosophy in mind.

Installation

Getting started with react-store-js is a breeze. Simply install it using npm:

npm i react-store-js 
Enter fullscreen mode Exit fullscreen mode

Usage

Initializing Global State
To begin, initialize your global state using the createWritableStore function:

// counter.store.ts import { createWritableStore } from "react-store-js"; export const counter = createWritableStore(0); 
Enter fullscreen mode Exit fullscreen mode

Using in Components

Now, in your React component, import the created store and employ the useWritable hook to interact with the state:

// App.tsx import { useWritable } from "react-store-js"; import { counter } from "./counter.store"; export default function App() { const $counter = useWritable(counter); return ( <div> <button onClick={() => $counter.update(($counter) => $counter + 1)}> Count is {$counter.value} </button>  </div>  ); } 
Enter fullscreen mode Exit fullscreen mode

Features

Type-Safety and Generics
react-store-js is fully type-safe, allowing you to leverage TypeScript's power. Generics can be utilized to enhance the typing of your states.

createWritableStore: Creates a mutable state for reading and updating.

createReadableStore: Creates a read-only state.

getStore: Retrieves the state directly.

Hooks

  • useWritable: Mutate, update, and read the state.

  • useReadable: Read from read-only states.

  • useDerived: Create a state based on other states.

  • useSubscriber: Listen for state changes.

Advanced Examples

Inside Mutation with createReadableStore:

// time.store.ts export const time = createReadableStore(0, (set) => { const intervalId = setInterval(() => set(Date.now()), 1000); return () => clearInterval(intervalId); }); 
Enter fullscreen mode Exit fullscreen mode

Inside Mutation with createWritableStore:

// time.store.ts export const time = createWritableStore(0, (set) => { const intervalId = setInterval(() => set(Date.now()), 1000); return () => clearInterval(intervalId); }); 
Enter fullscreen mode Exit fullscreen mode

react-store-js empowers React developers with a flexible and intuitive state management solution. Its simplicity, coupled with advanced features, makes it a valuable addition to your toolkit. Give it a try and elevate your React application's state management to the next level!

Top comments (0)