'Is there a way to override what useMemo does to determine if there's a change?
useMemo(() => expensiveFunction(), [deps]) re-executes the expensiveFunction when the deps have changed. I was wondering... is there a way to control how React will check if the deps have changed?
I would like to see if I can do a "deep" isEqual check of the dependencies rather than the shallow check much like what I did with using useReducer to implement useDeepState
import isEqual from "lodash.isequal";
import { Dispatch, useReducer } from "react";
/**
* This is similar to the `React.useState` function except it uses
* [lodash.isEqual](https://lodash.com/docs/4.17.15#isEqual) to perform a
* deep comparison of the values.
* @param initialState initial state
* @returns state, setter
* @category React State
*/
export function useDeepState<S>(initialState: S | (() => S)): [S, Dispatch<S>] {
function newStateIfNotEqual(state: S, newState: S) {
return isEqual(state, newState) ? state : newState;
}
if (typeof initialState === "function") {
return useReducer(
newStateIfNotEqual,
null as unknown as S,
initialState as () => S
);
} else {
return useReducer(
newStateIfNotEqual,
initialState
);
}
}
https://github.com/trajano/react-hooks/blob/master/src/useStates/useDeepState.ts
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
