Skip to content

Commit

Permalink
feat(useControlledState): support update callback with additional par…
Browse files Browse the repository at this point in the history
…ams (#1688)
  • Loading branch information
ValeraS authored Jul 2, 2024
1 parent a178dff commit 8bff882
Showing 1 changed file with 9 additions and 9 deletions.
18 changes: 9 additions & 9 deletions src/hooks/useControlledState/useControlledState.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import React from 'react';

export function useControlledState<T, C = T>(
export function useControlledState<T, C = T, Args extends any[] = []>(
value: Exclude<T, undefined>,
defaultValue: Exclude<T, undefined> | undefined,
onChange?: (v: C, ...args: any[]) => void,
): [T, (value: C) => void];
export function useControlledState<T, C = T>(
onChange?: (v: C, ...args: Args) => void,
): [T, (value: C, ...args: Args) => void];
export function useControlledState<T, C = T, Args extends any[] = []>(
value: Exclude<T, undefined> | undefined,
defaultValue: Exclude<T, undefined>,
onChange?: (v: C, ...args: any[]) => void,
): [T, (value: C) => void];
export function useControlledState<T, C extends T = T>(
onChange?: (v: C, ...args: Args) => void,
): [T, (value: C, ...args: Args) => void];
export function useControlledState<T, C extends T = T, Args extends any[] = []>(
value: T,
defaultValue: T,
onUpdate?: (value: C, ...args: any[]) => void,
onUpdate?: (value: C, ...args: Args) => void,
) {
const [innerValue, setInnerValue] = React.useState(value ?? defaultValue);

Expand All @@ -37,7 +37,7 @@ export function useControlledState<T, C extends T = T>(
// that we call `onUpdate` inside the callback function and onUpdate
// in a controlling component frequently calls setState itself,
// therefore we call `setState` while we're rendering a different component.
(newValue: C, ...args: any[]) => {
(newValue: C, ...args: Args) => {
if (!Object.is(currentValue, newValue)) {
onUpdate?.(newValue, ...args);
}
Expand Down

0 comments on commit 8bff882

Please sign in to comment.