Skip to content
Merged
Show file tree
Hide file tree
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"type": "patch",
"comment": "feat: defers useControllableState state to initializer method",
"packageName": "@fluentui/react-utilities",
"email": "[email protected]",
"dependentChangeType": "patch"
}
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,19 @@ export type UseControllableStateOptions<State> = {
export const useControllableState = <State>(
options: UseControllableStateOptions<State>,
): [State, React.Dispatch<React.SetStateAction<State>>] => {
const initialState = typeof options.defaultState === 'undefined' ? options.initialState : options.defaultState;
const [internalState, setInternalState] = React.useState<State>(initialState);
const [internalState, setInternalState] = React.useState<State>(() => {
if (options.defaultState === undefined) {
return options.initialState;
}
return isInitializer(options.defaultState) ? options.defaultState() : options.defaultState;
});
return useIsControlled(options.state) ? [options.state, noop] : [internalState, setInternalState];
};

function isInitializer<State>(value: State | (() => State)): value is () => State {
return typeof value === 'function';
}

function noop() {
/* noop */
}
Expand All @@ -53,7 +61,7 @@ function noop() {
* Prints an error when isControlled value switches between subsequent renders
* @returns - whether the value is controlled
*/
const useIsControlled = <V>(controlledValue?: V): controlledValue is V => {
const useIsControlled = <V>(controlledValue: V | undefined): controlledValue is V => {
const [isControlled] = React.useState<boolean>(() => controlledValue !== undefined);

if (process.env.NODE_ENV !== 'production') {
Expand Down