Skip to content

Instantly share code, notes, and snippets.

@byteab
Created February 21, 2025 17:46
Show Gist options
  • Save byteab/1a4583c5ec7f5020d2b64ee599a0937b to your computer and use it in GitHub Desktop.
Save byteab/1a4583c5ec7f5020d2b64ee599a0937b to your computer and use it in GitHub Desktop.
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