usePreservedReference
usePreservedReference
is a React hook that helps maintain the reference of a value when it hasn't changed, while ensuring you can safely use the latest state. It prevents unnecessary re-renders while always allowing access to the latest data.
Interface
ts
function usePreservedReference<T extends NotNullishValue>(
value: T,
areValuesEqual: (a: T, b: T) => boolean
): T;
Parameters
- valuerequired · T
The value to maintain the reference for. It returns a new reference if the state value changes after comparison.
- areValuesEqual(a: T, b: T) => boolean
An optional function to determine if two values are equal. By default, it uses
JSON.stringify
for comparison.
Return Value
- T
the same reference if the value is considered equal to the previous one, otherwise returns a new reference.
Example
tsx
import { usePreservedReference } from 'react-simplikit';
import { useState } from 'react';
function ExampleComponent() {
const [state, setState] = useState({ key: 'value' });
const preservedState = usePreservedReference(state);
return <div>{preservedState.key}</div>;
}