DEV Community

Anxiny
Anxiny

Posted on • Edited 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

Example:

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

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

Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)