@puhi8/react-utils
v1.0.0
Published
React hooks and utilities.
Readme
reactobjectstate
A tiny React hook for updating object state with partial patches.
Install
npm install reactobjectstateUsage
import { useObjectState } from "reactobjectstate";
function ProfileForm() {
const [profile, setProfile, resetProfile] = useObjectState({
firstName: "",
lastName: "",
subscribed: false,
});
return (
<form>
<input
value={profile.firstName}
onChange={(event) => setProfile({ firstName: event.target.value })}
/>
<input
value={profile.lastName}
onChange={(event) => setProfile({ lastName: event.target.value })}
/>
<label>
<input
type="checkbox"
checked={profile.subscribed}
onChange={(event) => setProfile({ subscribed: event.target.checked })}
/>
Subscribe
</label>
<button type="button" onClick={resetProfile}>
Reset
</button>
</form>
);
}setProfile also accepts an updater function when the next patch depends on the previous state:
setProfile((previous) => ({
subscribed: !previous.subscribed,
}));API
useObjectState(initialState)
Returns a readonly tuple:
const [state, setPartialState, resetState] = useObjectState(initialState);state: the current object state.setPartialState(patch): shallow-merges a partial object into the current state.setPartialState((previous) => patch): computes and shallow-merges a patch from the previous state.resetState(): restores the latestinitialStatevalue passed to the hook.
License
MIT
