Function to update state values (single key-value, batch object, or async functions)
function MyComponent() {
const setState = useSetState();
const {userName, count, loading} = useGetState({
userName: (state) => state.user?.name || 'Guest',
count: (state) => state.items?.length || 0,
loading: (state) => state.loading || false,
});
const handleStaticUpdate = () => {
// Static value update
setState('user', { name: 'John Doe', id: 123 });
};
const handleAsyncUpdate = async () => {
// Async function update
await setState('user', async (currentState) => {
const userData = await fetchUser(currentState.selectedUserId);
return userData;
});
};
const handleBatchUpdate = () => {
// Batch update with mixed static and async
setState({
loading: true,
user: async (state) => await fetchUser(state.userId),
items: [1, 2, 3, 4, 5],
lastUpdated: new Date().toISOString(),
});
};
const handleSyncFunction = () => {
// Sync function update
setState('count', (state) => (state.items?.length || 0) + 1);
};
return (
<div>
<h1>Hello, {userName}!</h1>
<p>You have {count} items</p>
{loading && <p>Loading...</p>}
<button onClick={handleStaticUpdate}>Static Update</button>
<button onClick={handleAsyncUpdate}>Async Update</button>
<button onClick={handleBatchUpdate}>Batch Update</button>
<button onClick={handleSyncFunction}>Increment Count</button>
</div>
);
}
Hook that provides state update functionality with async support. Handles both static values and async/sync functions that receive current state.