let-state v2.0.0
Let-State Library
The let-state
library provides a simple way to manage state in your react applications. This guide will walk you through setting up and using the store
and useStore
functions. you can have as many stores as you want.
Usage
check sample code here.
Creating a Store
To create a store, you need to define an initial state and a set of setters that will modify the state. Here's an example:
import { store } from 'let-state';
let state = {
count: 0,
isLoading: false,
data: [],
};
// setters are optional
const setters = {
incr() {
state = { count: state.count + 1 };
},
setIsLoading(isLoading) {
state = { ...state, isLoading };
},
setData(data) {
state = { ...state, data };
},
};
// actions are optional
const actions = {
async fetchData() {
setters.setIsLoading(true);
const data = await fetch('https://api.example.com/data');
setters.setData(data);
setters.setIsLoading(false);
},
};
// getters are optional
const getters = {
getDoubledCount() {
return state.count * 2;
},
};
export const countStore = store({
getState: () => state,
setters,
actions,
getters,
});
In this example, we define a countStore
with an initial state where count
is 0
. We also define a setter incr
that increments the count.
Using the Store
To use the store in your application, you can use the useStore
function. This function allows you to access the current state and the setters:
import { useStore } from 'let-state';
import { countStore } from './path/to/your/store';
const App = () => {
const { count, incr } = useStore(countStore);
return <div onClick={incr}>{count}</div>;
};
using with react-store-explorer to view and track state changes
npm install react-store-explorer
import { storeExplorer } from 'react-store-explorer';
const App = () => {
const { count, incr } = useStore(countStore);
return <StoreExplorer stores={{countStore}}> <div onClick={incr}>{count}</div> </StoreExplorer>;
};
In this example, useStore
is used to destructure the current count
and the incr
setter from the countStore
. You can then use count
to access the current state and incr
to update it.
Conclusion
The let-state
library provides a straightforward way to manage state in your applications. By defining stores and using them with useStore
, you can easily keep track of and update your application's state.