Skip to content

Instantly share code, notes, and snippets.

@kylewlacy
Created June 13, 2025 09:24
Show Gist options
  • Select an option

  • Save kylewlacy/0db5e03e5a34b12eb5d7b6c180dca185 to your computer and use it in GitHub Desktop.

Select an option

Save kylewlacy/0db5e03e5a34b12eb5d7b6c180dca185 to your computer and use it in GitHub Desktop.
useDeepState - React useState hook that uses fast-deep-equal to avoid unnecessary state changes
import React from "react";
import deepEqual from "fast-deep-equal";
export function useDeepState<S>(
initialState: S | (() => S),
): [S, React.Dispatch<React.SetStateAction<S>>] {
const [value, setValue] = React.useState(initialState);
const deepSetValue: React.Dispatch<React.SetStateAction<S>> =
React.useCallback((action) => {
setValue((prevValue) => {
const newValue: S =
typeof action === "function"
? (action as (prevValue: S) => S)(prevValue)
: action;
return deepEqual(prevValue, newValue) ? prevValue : newValue;
});
}, []);
return [value, deepSetValue];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment