Created
June 29, 2023 04:25
-
-
Save srikiranvelpuri/36bdf39f049d2863906faa10fc501a95 to your computer and use it in GitHub Desktop.
React custom hook to handle state as an object in functional components similar to local state management in class based components.
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 React, { useState } from 'react'; | |
import { isEmpty, isNil } from 'ramda'; | |
/** | |
* Custom hook to handle state as an object in functional components similar to local state management in class based components. | |
** Returns a stateful value and a function to update it. | |
* @param {object} initialStateObj | |
* @returns { [{},React.Dispatch<React.SetStateAction<{}>>]} | |
*/ | |
const useStateObj = (initialStateObj = {}) => { | |
const [state, setState] = useState(initialStateObj); | |
const setStateObj = (updatedState) => { | |
if (typeof updatedState === 'function') { | |
setState((prevState) => { | |
const newState = updatedState(prevState); | |
if (isNil(newState) || isEmpty(newState)) { | |
return initialStateObj; | |
} | |
return newState; | |
}); | |
} else if (isNil(updatedState) || isEmpty(updatedState)) { | |
setState(initialStateObj); | |
} else { | |
setState((prevState) => ({ ...prevState, ...updatedState })); | |
} | |
}; | |
return [state, setStateObj]; | |
}; | |
export default useStateObj; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment