@okaygift/use-object-state
v1.0.0
Published
A simple React hook to update object state without needing to manually spread the previous state.
Maintainers
Readme
Use Object State Hook A simple React hook to update object state without needing to manually spread ...prevState every time.
The Problem When using the standard useState hook with an object, updating a single property is verbose. You must always remember to spread the previous state to avoid overwriting the other properties:
const [user, setUser] = useState({ name: 'Alex', role: 'user' });
// To update just the role: const makeAdmin = () => { setUser(prevUser => ({ ...prevUser, // This part is repetitive role: 'admin', })); };
The Solution useObjectState provides an updater function that automatically merges partial updates into the existing state, making your code cleaner and less error-prone.
import { useObjectState } from 'use-object-state';
const [user, updateUser] = useObjectState({ name: 'Alex', role: 'user' });
// Now you only need to provide the properties you want to change: const makeAdmin = () => { updateUser({ role: 'admin' }); };
// It also supports the function update form! const makeAdmin = () => { updateUser(prevUser => ({ //... some logic with prevUser role: 'admin' })) }
Installation npm install use-object-state
API useObjectState(initialState) Parameters initialState (required): The initial object value for your state.
Returns An array tuple [state, updateState]:
state: The current state object.
updateState: A function to update the state. It accepts a partial state object that will be merged into the current state.
