Created
February 21, 2025 17:46
-
-
Save byteab/1a4583c5ec7f5020d2b64ee599a0937b to your computer and use it in GitHub Desktop.
This file contains 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 { useCallback, useReducer } from 'react'; | |
type SetAction<V> = { type: 'SET'; payload: V | ((prev: V) => V) }; | |
function solidStateReducer<V>(state: V, action: SetAction<V>): V { | |
const nextState = | |
typeof action.payload === 'function' | |
? (action.payload as (prev: V) => V)(state) | |
: action.payload; | |
return Object.is(state, nextState) ? state : nextState; | |
} | |
/** | |
* useSolidState is a state hook that only updates when the new state is different. | |
* It supports both direct state values and functional updates. | |
*/ | |
export function useSolidState<V>(initialValue: V) { | |
const [state, dispatch] = useReducer(solidStateReducer, initialValue); | |
const setState = useCallback( | |
(value: V | ((prev: V) => V)) => { | |
dispatch({ type: 'SET', payload: value }); | |
}, | |
[] | |
); | |
return [state, setState] as const; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment