Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix internal state consistency of control cards in controlled mode #6771

Merged
merged 2 commits into from
Apr 19, 2024

Conversation

gluxon
Copy link
Contributor

@gluxon gluxon commented Apr 18, 2024

Problem

Repro

In an application using React 18 with the createRoot API, a <RadioCard> in controlled mode may not reflect the current controlled checked prop value. Note in the video below how two clicks are required to get the radio button in its checked state.

Problem.mov

Here's the code for the video above.

import { RadioCard } from '@blueprintjs/core'
import React from 'react'

function App() {
  const [testState, setTestState] = React.useState<"toast" | "bread">("toast")

  return (
    <div>
      {testState}
      <RadioCard checked={testState === "toast"} onClick={() => { setTestState("toast"); }}>
        toast
      </RadioCard>
      <RadioCard checked={testState === "bread"} onClick={() => { setTestState("bread"); }}>
        bread
      </RadioCard>
    </div>
  )
}

export default App

Explanation

The repro code above contains buggy code. It's passing a controlled checked prop, but using onClick instead of onChange to toggle that prop.

This causes <RadioCard>'s internal state tracking to be inconsistent, which is arguably still a Blueprint bug despite the buggy usage this component.

With the concurrent renderer

  1. The onClick handler on <RadioCard> fires.
  2. This changes the props.checked value, and triggers the useEffect here. The effect changes the button's checked state from false to true.
    const [checked, setChecked] = React.useState(() => props.defaultChecked ?? false);
    React.useEffect(() => {
    if (props.checked !== undefined) {
    setChecked(props.checked);
    }
    }, [props.checked]);
  3. The <RadioCard>'s onChange handler then fires, toggling the updated checked state from true back to false. 🤦🏻‍♂️
    const onChange = React.useCallback<React.ChangeEventHandler<HTMLInputElement>>(
    e => {
    setChecked(c => !c);

Legacy renderer

With the legacy React 17 renderer, this happened to work because the order of these event handlers are reversed.

  1. The onClick handler on <RadioCard> fires.
  2. The internal onChange handler fires first.
  3. Then the useEffect fires second.

I believe the order is different with the concurrent renderer due to an intentional change to make useEffect's timing more consistent.

Summary

In summary of the explanation above, Blueprint's uncontrolled state handling is fighting with the controlled state handling of the application.

Changes

The useEffect here is an example of "you might not need an effect".

React.useEffect(() => {
if (props.checked !== undefined) {
setChecked(props.checked);
}
}, [props.checked]);

I think we can simplify this with a value that's "calculated during rendering".

When something can be calculated from the existing props or state, don’t put it in state. Instead, calculate it during rendering. This makes your code faster (you avoid the extra “cascading” updates), simpler (you remove some code), and less error-prone (you avoid bugs caused by different state variables getting out of sync with each other). If this approach feels new to you, Thinking in React explains what should go into state.

const checked = props.checked ?? checkedStateForUncontrolledMode;

@changelog-app
Copy link

changelog-app bot commented Apr 18, 2024

Generate changelog in packages/core/changelog/@unreleased

What do the change types mean?
  • feature: A new feature of the service.
  • improvement: An incremental improvement in the functionality or operation of the service.
  • fix: Remedies the incorrect behaviour of a component of the service in a backwards-compatible way.
  • break: Has the potential to break consumers of this service's API, inclusive of both Palantir services
    and external consumers of the service's API (e.g. customer-written software or integrations).
  • deprecation: Advertises the intention to remove service functionality without any change to the
    operation of the service itself.
  • manualTask: Requires the possibility of manual intervention (running a script, eyeballing configuration,
    performing database surgery, ...) at the time of upgrade for it to succeed.
  • migration: A fully automatic upgrade migration task with no engineer input required.

Note: only one type should be chosen.

How are new versions calculated?
  • ❗The break and manual task changelog types will result in a major release!
  • 🐛 The fix changelog type will result in a minor release in most cases, and a patch release version for patch branches. This behaviour is configurable in autorelease.
  • ✨ All others will result in a minor version release.

Type

  • Feature
  • Improvement
  • Fix
  • Break
  • Deprecation
  • Manual task
  • Migration

Description

Fix a case where a control card component (e.g. <RadioCard>) may have rendered with a checked state that does not match its checked prop. This can happen if that prop was changed outside of an onChange handler and in an onClick handler instead.

Check the box to generate changelog(s)

  • Generate changelog entry

@gluxon gluxon marked this pull request as ready for review April 18, 2024 22:08
@svc-palantir-github
Copy link

Add generated changelog entries

Build artifact links for this commit: documentation | landing | table | demo

This is an automated comment from the deploy-preview CircleCI job.

Copy link
Contributor

@pgoldberg pgoldberg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We really don't need an effect here. Excellent example of https://react.dev/learn/you-might-not-need-an-effect

Thank you for the detailed description!

@gluxon gluxon merged commit bca2e05 into develop Apr 19, 2024
13 checks passed
@gluxon gluxon deleted the fix-ControlCard-internal-consistency branch April 19, 2024 20:06
@gluxon
Copy link
Contributor Author

gluxon commented Apr 19, 2024

Thanks for the reviews @pgoldberg @styu

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.

5 participants