// 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',
});
Last active
September 26, 2021 11:02
-
-
Save Munawwar/1fef6af4065370758323491a2e3c97c9 to your computer and use it in GitHub Desktop.
Object state hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment