Skip to content

Instantly share code, notes, and snippets.

@srikiranvelpuri
Created June 29, 2023 04:25
Show Gist options
  • Save srikiranvelpuri/36bdf39f049d2863906faa10fc501a95 to your computer and use it in GitHub Desktop.
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.
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