Skip to content

Commit d9e306b

Browse files
authored
Revert "Update useControlledState for StrictMode" (#2265)
1 parent 0795617 commit d9e306b

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

packages/@react-stately/utils/src/useControlledState.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,10 +43,19 @@ export function useControlledState<T>(
4343

4444
if (typeof value === 'function') {
4545
// this supports functional updates https://reactjs.org/docs/hooks-reference.html#functional-updates
46-
let oldValue = stateRef.current;
47-
let interceptedValue = value(oldValue);
48-
setStateValue(!isControlled ? interceptedValue : oldValue);
49-
onChangeCaller(interceptedValue, ...args);
46+
// when someone using useControlledState calls setControlledState(myFunc)
47+
// this will call our useState setState with a function as well which invokes myFunc and calls onChange with the value from myFunc
48+
// if we're in an uncontrolled state, then we also return the value of myFunc which to setState looks as though it was just called with myFunc from the beginning
49+
// otherwise we just return the controlled value, which won't cause a rerender because React knows to bail out when the value is the same
50+
let updateFunction = (oldValue, ...functionArgs) => {
51+
let interceptedValue = value(isControlled ? stateRef.current : oldValue, ...functionArgs);
52+
onChangeCaller(interceptedValue, ...args);
53+
if (!isControlled) {
54+
return interceptedValue;
55+
}
56+
return oldValue;
57+
};
58+
setStateValue(updateFunction);
5059
} else {
5160
if (!isControlled) {
5261
setStateValue(value);

0 commit comments

Comments
 (0)