useCallbackDeepCompare
Custom useCallback that returns memoized callback that changes only if deps are different in depth.
Demo
INFO
The component has:
- a state useState variable with id and name properties.
- a message useState variable that's a string rendered in a tag p.
- a useCallback function that update message variable with state variable values.
- a useCallbackDeepCompare function that update message variable with state variable values.
- a button with a function attached to onClick event that increment state id property.
- a button with a useCallback function attached to onClick event.
- a button with a useCallbackDeepCompare function attached to onClick event.
useCallbackDeepCompare updates its state value and sets correct message since it compares changes in depth.
Loading demo…
Show source code
tsx
import { useCallback, useState } from "react";
import { useCallbackDeepCompare } from "../../../..";
const UseCallbackDeepCompare = () => {
const [state, setState] = useState({ id: 0, name: "state" });
const [message, setMessage] = useState("Nothing to show...");
const defaultCallback = useCallback(() => {
setMessage(`useCallback: id:${state.id} - name:${state.name}`);
}, [state]);
const callbackCompare = useCallbackDeepCompare(
() => {
setMessage(`useCallbackDeepCompare: id:${state.id} - name:${state.name}`);
},
[state]
);
return (<>
<p>Current state: id: {state.id} - name: {state.name}</p>
<p>{message}</p>
<button style={{margin: '0 .25rem'}} onClick={() => setState(t => ({ ...t, id: t.id + 1 }))}>Increment state counter</button>
<button style={{margin: '0 .25rem'}} onClick={defaultCallback}>Set defaultCallback message</button>
<button style={{margin: '0 .25rem'}} onClick={callbackCompare}>Set callbackCompare message</button>
</>);
};
UseCallbackDeepCompare.displayName = "UseCallbackDeepCompare";
export { UseCallbackDeepCompare };