Skip to main content

usePreservedState

A custom hook that preserves state using a given value and a comparator function.

If no comparator is provided, the isEqual function from @modern-kit/utils is used by default.

Whenever the given value changes, the hook compares the previous state with the new value using the comparator, and only updates the state when they are determined to be different.

This prevents unnecessary state updates.


Code

🔗 View source code


Interface

typescript
function usePreservedState<T>(
value: T,
comparator?: (source: T, target: T) => boolean
): T;

Options

NameTypeDefaultDescription
valueT-The value to preserve
comparator(source: T, target: T) => booleanisEqualFunction to compare the previous state with the new value. Should return true if the two values are equal

Usage

Default Comparator Usage

typescript
import React, { useEffect, useState } from "react";
import { usePreservedState } from "@modern-kit/react";

const Example = () => {
const preservedState = usePreservedState({ exampleId: 1 }); // The reference of preservedState is maintained even when the component re-renders.

return <>{/* ... */}</>;
}

Custom Comparator Usage

typescript
import React, { useEffect, useState } from 'react';
import { usePreservedState } from '@modern-kit/react';

const Example = () => {
const comparator = (
source: { exampleId: number },
target: { exampleId: number }
) => source.exampleId === target.exampleId;

const preservedState = usePreservedState({ exampleId: 1 }, comparator);

return <>{/* ... */}</>;
};