createScopedStore
The createScopedStore
function creates a new scoped store instance with a React context provider.
function createScopedStore<T>(props: ConstructorProps<T>): {
Provider: FC<{ children: React.ReactNode }>;
useStore: () => Store<T>;
};
Parameters
Option | Type | Required | Description |
---|---|---|---|
props | ConstructorProps<T> | Yes | Configuration options for the store. |
ConstructorProps<T>
Option | Type | Required | Description |
---|---|---|---|
initialData | NestedPartial<T> | No | The initial data for the store. |
fallbackData | NestedPartial<T> | No | Fallback data used when a value is not found in the main data. |
devTools | string | No | Name for Redux DevTools integration. If provided, enables DevTools support. |
Returns
An object with two properties:
Provider
: A React component that provides the store context to its children.useStore
: A hook that returns the store instance within the context.
Description
The createScopedStore
function creates a new scoped store instance that can be used within a specific part of your React component tree. It provides a context provider and a hook to access the store instance.
Example
import React from 'react';
import { createScopedStore } from '@devlab/store';
type UserStore = {
user: {
name: string;
age: number;
};
};
const { Provider, useStore } = createScopedStore<UserStore>({
initialData: {
user: {
name: 'John Doe',
age: 30
}
}
});
function UserProfile() {
const store = useStore();
const name = store.use('user.name');
const age = store.use('user.age');
return (
<div>
<p>Name: {name}</p>
<p>Age: {age}</p>
<button onClick={() => store.set('user.age', age + 1)}>
Increment Age
</button>
</div>
);
}
function App() {
return (
<Provider>
<h1>User Profile</h1>
<UserProfile />
</Provider>
);
}
This example demonstrates how to create a scoped store, provide it to a part of your component tree, and use it within a React component.