Skip to content

Instantly share code, notes, and snippets.

@Munawwar
Last active September 26, 2021 11:02
Show Gist options
  • Save Munawwar/1fef6af4065370758323491a2e3c97c9 to your computer and use it in GitHub Desktop.
Save Munawwar/1fef6af4065370758323491a2e3c97c9 to your computer and use it in GitHub Desktop.
Object state hook
import { useState } from 'react';
import { merge } from 'lodash';
function useObjectState(defaultVal = {}) {
const [state, setState] = useState(defaultVal);
const updateState = (newState) => {
setState((previousState) => ({ ...previousState, ...newState }));
};
const deepMergeState = (newState) => {
setState((previousState) => merge({}, previousState, newState));
};
return [state, setState, updateState, deepMergeState];
}
export default useObjectState;
// example usage:
const [timeRange, setTimeRange, updateTimeRange] = useObjectState({
  startTime: '00:00',
  endTime: '00:00',
});

updateTimeRange({ startTime: '14:00' });

const resetTime = () => setTimeRange({
  startTime: '00:00',
  endTime: '00:00',
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment