1.0.5 • Published 6 months ago
@reactx-hooks/extension v1.0.5
@reactx-hooks/extension
A collection of useful React hooks for managing complex state.
Installation
npm install @reactx-hooks/extension
# or
yarn add @reactx-hooks/extension
# or
bun add @reactx-hooks/extension
Usage
useModel
useModel
is a powerful hook for managing complex state objects with deep nesting. It provides a simple API for updating nested objects while maintaining immutability.
import { useModel } from '@reactx-hooks/extension';
interface User {
name: string;
age: number;
address: {
city: string;
country: string;
location: {
latitude: number;
longitude: number;
};
};
}
function UserProfile() {
const [user, setUser, resetUser] = useModel<User>({
initialValue: {
name: 'John Doe',
age: 30,
address: {
city: 'London',
country: 'UK',
location: {
latitude: 51.5074,
longitude: -0.1278
}
}
}
});
// Update nested values
const updateCity = () => {
setUser({
address: {
city: 'New York'
}
});
};
// Function updates
const updateLocation = () => {
setUser(prev => ({
address: {
location: {
latitude: prev.address.location.latitude + 1,
longitude: prev.address.location.longitude + 1
}
}
}));
};
return (
<div>
<h1>{user.name}</h1>
<p>City: {user.address.city}</p>
<button onClick={updateCity}>Update City</button>
<button onClick={updateLocation}>Update Location</button>
<button onClick={resetUser}>Reset</button>
</div>
);
}
Features
- Deep nested object updates
- Type-safe with TypeScript
- Optional initial value
- State change callback
- Reset functionality
- Immutable updates
- Partial updates support
API
function useModel<T extends object>(options?: {
initialValue?: T;
onStateChange?: (newState: T) => void;
}): [
T,
(updates: DeepPartial<T> | ((prevState: T) => DeepPartial<T>)) => void,
() => void
];
Options
initialValue
: Optional initial stateonStateChange
: Optional callback that runs when state changes
Returns
[0]
: Current state[1]
: Function to update state[2]
: Function to reset state to initial value
License
MIT