This content originally appeared on DEV Community and was authored by Ng Dream
Here's a README for your Pulsy package:
Pulsy
Pulsy is a lightweight, flexible state management library for React that supports persistence, middleware, memoization, and enhanced dev tools integration. This package enables you to easily create and manage state across your React application with advanced features like persistence to local storage and middleware to control state updates.
Features
- State Management: Manage global state across your application.
-
Persistence: Automatically save and load states to/from
localStorage
. - Middleware: Add custom logic to manipulate state updates.
- Dev Tools Integration: Built-in support for logging, time-travel debugging, and performance monitoring.
- Memoization: Optimize re-rendering by memoizing state values.
Installation
First, install the package using npm or yarn:
npm install pulsy
or
yarn add pulsy
Basic Usage
Pulsy allows you to create stores, use them in your components, and optionally configure persistence and middleware.
1. Initialize Pulsy
Before using Pulsy, configure the store with initializePulsy
. You can define multiple stores at once and configure persistence or memoization.
import { initializePulsy } from 'pulsy';
// Initializing Pulsy with default values
initializePulsy({
user: { name: 'John Doe', age: 30 },
theme: 'light',
}, {
enableDevTools: true,
persist: true,
});
2. Create and Use a Store
After initialization, you can use the usePulsy
hook in any React component to access and update the store.
import usePulsy from 'pulsy';
function UserProfile() {
const [user, setUser] = usePulsy('user');
const updateUser = () => {
setUser(prev => ({ ...prev, age: prev.age + 1 }));
};
return (
<div>
<h1>{user.name}</h1>
<p>Age: {user.age}</p>
<button onClick={updateUser}>Increase Age</button>
</div>
);
}
export default UserProfile;
In this example:
-
usePulsy('user')
retrieves the currentuser
store value and provides a setter function to update it. - The
updateUser
function increments the user's age, demonstrating how to update the state.
3. Persist State
By enabling persistence, Pulsy automatically saves the store to localStorage
. It also retrieves the value from localStorage
when the component mounts.
To persist a specific store during its creation, use the persist
option:
initializePulsy({
user: { name: 'John Doe', age: 30 },
theme: 'light',
}, {
persist: true, // Enable persistence globally
});
Pulsy will save the store state in localStorage
under the key pulsy_{storeName}
.
4. Middleware
You can add middleware to modify the store's value before it is set. For example, to log changes or restrict certain values:
import { addMiddleware } from 'pulsy';
// Middleware that ensures age cannot be set below 0
addMiddleware('user', (newValue, prevValue) => {
return { ...newValue, age: Math.max(newValue.age, 0) };
});
In this example:
- The middleware checks if the new
age
is below 0 and ensures it cannot be negative.
5. Namespaced Stores
You can create namespaced stores for better organization, especially when dealing with complex state structures:
import { createNamespacedStore } from 'pulsy';
const useUserStore = createNamespacedStore('user');
function UserSettings() {
const [userSettings, setUserSettings] = useUserStore('settings');
return <div>{JSON.stringify(userSettings)}</div>;
}
6. DevTools
Pulsy integrates with your app's development tools. By enabling enableDevTools
, Pulsy logs every store creation, update, and error to help with debugging:
initializePulsy({
user: { name: 'Jane Doe', age: 28 },
}, { enableDevTools: true });
API
initializePulsy(storeConfigs, config?)
Initializes Pulsy with a set of stores and optional global configurations.
-
storeConfigs
: An object defining the stores and their initial values. -
config
: Optional. APulsyConfig
object to customize global settings.
type PulsyConfig = {
enableDevTools?: boolean; // Enable dev tools logging
onStoreCreate?: (name: string, initialValue: any) => void; // Callback on store creation
onStoreUpdate?: (name: string, newValue: any) => void; // Callback on store update
persist?: boolean; // Enable persistence
defaultMemoize?: boolean; // Enable memoization
};
usePulsy(name)
The main hook to retrieve and update a store.
usePulsy<T>(name: string): [T, (newValue: T | (prevValue: T) => T) => Promise<void>];
-
name
: The name of the store. - Returns a tuple:
[storeValue, setStoreValue]
.
createStore(name, initialValue, options?)
Creates a new store manually.
-
name
: The name of the store. -
initialValue
: The initial value of the store. -
options
: Optional configuration for persistence, middleware, or memoization.
setStoreValue(name, value)
Sets the value of a store.
-
name
: The store name. -
value
: The new value for the store.
addMiddleware(name, middleware)
Adds middleware to an existing store.
-
name
: The store name. -
middleware
: A function to modify the store value during updates.
clearPersistedStores()
Clears all persisted store values from localStorage
.
clearPersistedStores();
Advanced Features
Memoization
You can enable memoization on a store to avoid unnecessary renders when the value doesn't change.
initializePulsy({
user: { name: 'Jane Doe', age: 28 },
}, { defaultMemoize: true });
Time-Travel
Pulsy supports time-travel debugging, allowing you to step back and forth through store updates. This can be configured with devTools
.
License
This package is released under the MIT License.
This README covers basic installation, usage, and advanced features of Pulsy. You can add more advanced examples or custom configurations as your package evolves!
This content originally appeared on DEV Community and was authored by Ng Dream
Ng Dream | Sciencx (2024-09-24T01:28:54+00:00) Pulsy , a simple react state management library. Retrieved from https://www.scien.cx/2024/09/24/pulsy-a-simple-react-state-management-library/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.