beautiful-react-hooks
Version:
A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development
20 lines (19 loc) • 649 B
JavaScript
import { useMemo, useState } from 'react';
/**
* Returns a reactive value that can be used as a state.
*/
const useMutableState = (initialState) => {
if (typeof initialState !== 'object' || initialState === null)
throw new Error('The initial state must be an object');
const [, setState] = useState(0);
return useMemo(() => new Proxy(initialState, {
set: (target, prop, value) => {
if (target && target[prop] !== value) {
target[prop] = value;
setState((state) => (state + 1));
}
return true;
}
}), []);
};
export default useMutableState;