Created
June 13, 2025 09:24
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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