This is a simple yet powerful global state management library built using React's useSyncExternalStore. It allows you to manage global state across multiple components, handle both primitive and object states, and optionally persist the state using localStorage.
- Global State Management: Easily manage state across multiple components without prop drilling.
- Primitive and Object State Support: Handle both primitive types (e.g., numbers, strings) and complex objects.
- State Persistence: Optionally persist state using
localStoragewith a simple configuration. - Partial Object Updates: Perform partial updates to object state without overriding the entire object.
-
Clone the repository:
git clone https://github.com/codewithwaheed/zorx.git cd zorx -
Install dependencies:
npm install
You can create a global store using the createUseStore function. It supports both primitive and object states and can persist the state to localStorage.
// src/store.ts
import { useSyncExternalStore } from "react";
export type Listener = () => void;
function createStore<T>({
initialState,
key,
}: {
initialState: T;
key?: string;
}) {
let subscribers: Listener[] = [];
let state = initialState;
// Load persisted state from localStorage
if (key && typeof window !== "undefined") {
const persistedState = localStorage.getItem(key);
if (persistedState) {
try {
const parsedState = JSON.parse(persistedState);
if (typeof parsedState === typeof initialState) {
state = parsedState;
}
} catch (error) {
console.error("Error parsing state from localStorage", error);
}
}
}
const notifyStateChanged = () => {
subscribers.forEach((fn) => fn());
};
const persistState = (newState: T) => {
if (key && typeof window !== "undefined") {
localStorage.setItem(key, JSON.stringify(newState));
}
};
return {
subscribe(fn: Listener) {
subscribers.push(fn);
return () => {
subscribers = subscribers.filter((listener) => listener !== fn);
};
},
getSnapshot() {
return state;
},
setState(newState: Partial<T> | T) {
if (typeof newState === "object" && !Array.isArray(newState)) {
state = { ...(state as object), ...newState };
} else {
state = newState as T;
}
notifyStateChanged();
persistState(state);
},
};
}
export function createUseStore<T>(initialState: T, key?: string) {
const store = createStore({ initialState, key });
return () =>
[
useSyncExternalStore(store.subscribe, store.getSnapshot),
store.setState,
] as const;
}For managing a simple primitive state (like a number), create a store and use it inside your component.
// example/globalStore.ts
import { createUseStore } from "../src/store";
export const useCountStore = createUseStore<number>(0, "countState"); // Using localStorage to persistThen, in your component, you can easily increment or decrement the count:
// example/Counter.tsx
import React from "react";
import { useCountStore } from "./globalStore";
const Counter = ({ index }: { index: number }) => {
const [count, setCount] = useCountStore();
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return (
<div>
<h2>
Counter {index}: {count}
</h2>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;For more complex state management, you can manage an object state and perform partial updates:
// example/globalStore.ts
import { createUseStore } from "../src/store";
interface State {
count: number;
user: {
name: string;
city: string;
};
}
export const useGlobalStore = createUseStore<State>(
{
count: 0,
user: {
name: "Alice",
city: "Berlin",
},
},
"globalAppState"
);In your component, you can update only specific properties of the object:
// example/UserComponent.tsx
import React from "react";
import { useGlobalStore } from "./globalStore";
export function UserComponent() {
const [{ count, user }, setGlobalState] = useGlobalStore();
const increment = () => {
setGlobalState({ count: count + 1 });
};
const changeCity = () => {
setGlobalState({ user: { ...user, city: "Hamburg" } }); // Partial update
};
return (
<div>
<h2>Count: {count}</h2>
<p>User: {user.name}</p>
<p>City: {user.city}</p>
<button onClick={increment}>Increment Count</button>
<button onClick={changeCity}>Change City</button>
</div>
);
}To run the example:
npm run devThe example application will start, showcasing the use of both primitive and object-based state management.
- Initial State: You can pass any initial state to
createUseStore— either a primitive or an object. - Persistence: By providing a
keytocreateUseStore, the state will be automatically persisted inlocalStorageand restored when the app reloads.
Feel free to open issues and submit pull requests for any improvements or bug fixes. Contributions are welcome!
This project is licensed under the MIT License.