In Simple react class component we used to change the props to state this way:
constructor(props) {
super(props)
this.state = {
pitch: props.book
It is difficult to achieve a state which depends on prop value and at the same avoid unnecessary re-renders.
Here is my attempt in creating such a hook:
/**
* Replacement for useState which depends on prop value and avoids unnecessary re-renders.
*/
export function useStateBasedOnProps(propValue) {
const [, update] = useState(false);
const [state, setState] = useMemo(() => {
const state = {};
return [
state,
(value) => {
if (value instanceof Function) {
state.value = value(state.value);
} else {
state.value = value;
}
update((tick) => !tick);
}
];
}, [update]);
if (state.prevPropValue !== propValue) {
state.prevPropValue = propValue;
state.value = propValue;
}
return [state.value, setState];
}
Here is a usage example:
function IncButton({initialValue}) {
const [value, setValue] = useStateBasedOnProps(initialValue);
const increment = useCallback(() => setValue((prev) => prev + 1), [setValue]);
return ;
}
Full example: https://gist.github.com/mdevils/b861610780300784292194f65886517a