Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions src/hooks/useControlledState/useControlledState.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,15 @@
import { type Dispatch, type SetStateAction, useCallback, useState } from 'react';
import React, { type Dispatch, type SetStateAction, useCallback, useRef, useState } from 'react';

const useInsertionEffect = (React as Record<string, unknown>)[
`useInsertionEffect${Math.random().toFixed(1)}`.slice(0, -3)
];
const useSafeInsertionEffect =
// React 17 doesn't have useInsertionEffect.
typeof useInsertionEffect === 'function' &&
// Preact replaces useInsertionEffect with useLayoutEffect and fires too late.
useInsertionEffect !== React.useLayoutEffect
? useInsertionEffect
: (fn: React.EffectCallback) => fn();

type ControlledState<T> = { value: T; defaultValue?: never } | { defaultValue: T; value?: T };

Expand Down Expand Up @@ -52,16 +63,22 @@ export function useControlledState<T>({
const controlled = valueProp !== undefined;
const value = controlled ? valueProp : uncontrolledState;

const onChangeRef = useRef(onChange);

useSafeInsertionEffect(() => {
onChangeRef.current = onChange;
}, [onChange]);

const setValue = useCallback(
(next: SetStateAction<T>) => {
const nextValue = isSetStateAction(next) ? next(value) : next;

if (equalityFn(value, nextValue) === true) return;
if (controlled === false) setUncontrolledState(nextValue);
if (controlled === true && nextValue === undefined) setUncontrolledState(nextValue);
onChange?.(nextValue);
onChangeRef.current?.(nextValue);
},
[controlled, onChange, equalityFn, value]
[controlled, equalityFn, value]
);

return [value, setValue];
Expand Down