DEV Community


Posted on • Updated on


Custom React Hook - useObjectState

A custom hook that make things easier with object state.

function useObjectState(defaultValue = {},defaultFieldValue = null) {
  const [obj, setObj] = useState(defaultValue);
  const update = (key, value) => {
    setObj({ ...obj, [key]: value });
  const get = (key, defaultValue=null) => {
    if(!key)return obj;
    return obj[key] ?? defaultValue ?? defaultFieldValue;
  return [get, update, setObj];
Enter fullscreen mode Exit fullscreen mode


function SomeForm({defaultData}){
    const [get,update]=useObjectState(defaultData, '');

    return <form>
            <input value={get('name','John Doe')} onChange={(e)=>update('name',} />
            <input value={get('address')} onChange={(e)=>update('address',} />

Enter fullscreen mode Exit fullscreen mode

Thank you all! Please feel free to leave any comments.

Top comments (0)

Visualizing Promises and Async/Await 🤯

async await

Learn the ins and outs of Promises and Async/Await!