Skip to content

fix(useControlledState): fix multiple function set state actions problem - #344

Closed
kyukyu-dev wants to merge 2 commits into
toss:mainfrom
kyukyu-dev:fix/fix-useConrolledState-multiple-function-setState
Closed

fix(useControlledState): fix multiple function set state actions problem#344
kyukyu-dev wants to merge 2 commits into
toss:mainfrom
kyukyu-dev:fix/fix-useConrolledState-multiple-function-setState

Conversation

@kyukyu-dev

@kyukyu-dev kyukyu-dev commented Mar 12, 2026

Copy link
Copy Markdown
Contributor

Overview

This PR improves useControlledState to correctly handle multiple functional setState actions executed within the same render cycle.

Previously, functional updates relied on a closure-captured value, which could lead to stale state when multiple updates were batched by React. This change introduces an internal valueRef to always compute the next state from the latest intermediate value.

Additionally, a safe insertion/layout effect is used to keep the ref synchronized with the actual state after each render, ensuring consistent behavior in both controlled and uncontrolled modes.

Problem

useControlledState previously calculated the next value using the value captured in the closure.

const nextValue = isSetStateAction(next) ? next(value) : next;

When multiple functional setState actions were executed within the same render cycle, each updater received the same stale value, because React batches updates.

Example:

setValue(prev => prev + 3);
setValue(prev => prev + 3);

Expected result: 5 → 8 → 11

Actual result: 5 → 8

Both updates used the same previous value (5).

Solution

To ensure each updater receives the latest intermediate value, this PR introduces an internal valueRef.

const valueRef = useRef(uncontrolledState);

The setter now computes updates based on valueRef.current:

const nextValue = isSetStateAction(next) ? next(valueRef.current) : next;

After computing the next value, the ref is updated immediately:

valueRef.current = nextValue;

This ensures subsequent functional updates in the same render cycle receive the correct latest value.

Ref synchronization

Since the ref may be optimistically updated before React commits the actual value, we resync it after each render using a safe insertion/layout effect:

useSafeInsertionEffect(() => {
  valueRef.current = value;
});

This keeps the ref consistent with the real state value.

Controlled mode edge case

In controlled mode, the parent may choose not to update the value.
To ensure the ref resynchronizes correctly in that case, a forced re-render is triggered:

const [, triggerRerender] = useReducer(() => ({}), {});

...

triggerRerender();

Result

useControlledState now correctly handles multiple functional updates:

setValue(prev => prev + 3);
setValue(prev => prev + 3);

// 5 → 8 → 11

without stale closure issues.

Checklist

  • Did you write the test code?
  • Have you run yarn run fix to format and lint the code and docs?
  • Have you run yarn run test:coverage to make sure there is no uncovered line?
  • Did you write the JSDoc?

@kyukyu-dev kyukyu-dev changed the title Fix/fix use conrolled state multiple function set state fix(useControlledState): use controlled state multiple function set state Mar 12, 2026
@kyukyu-dev kyukyu-dev changed the title fix(useControlledState): use controlled state multiple function set state fix(useControlledState): fix multiple function set state actions problem Mar 12, 2026
@hyesungoh

Copy link
Copy Markdown
Member

Hi @kyukyu-dev, thanks a lot for tracking this down and for the fix, and sorry for the long silence on our side.

We confirmed the bug: two function updates in the same tick both see the same prev, in both modes.

While reviewing, we also found that this implementation can cause an infinite render loop. The forced re-render fires even when the parent rejects the change, so any caller that re-issues setValue on every render never settles:

function App() {
  const [value, setValue] = useState(10);
  const [state, setState] = useControlledState({
    value,
    onChange: next => setValue(Math.min(next, 10)), // parent clamps, effectively rejects 12
  });

  useLayoutEffect(function push() {
    setState(12); // no deps: runs on every render
  });

  return <p>{state}</p>;
}
// current main: settles at 10
// this PR: "Maximum update depth exceeded"

The same thing happens with the more common mistake of passing a fresh object in an effect's deps. A useEffect variant doesn't even hit React's guard and just spins.

Weighing the two, we decided to fix the ordering only in uncontrolled mode, where React's own update queue can do it with no extra re-render (the same trade-off Radix makes in useControllableState). In controlled mode, two function updates in the same tick still see the same prev. We think that combination is rare enough in practice, and an infinite loop in ordinary code is the worse failure.

That fix is up in #484 with you as a co-author, since it builds on your test case. I'll close this one in favor of it, but if you see a way to get both, please do speak up. Thanks again!

@hyesungoh hyesungoh closed this Sep 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants