statelyai / xstate

Actor-based state management & orchestration for complex app logic.
https://stately.ai/docs
MIT License
27.21k stars 1.26k forks source link

Avoid calling `selector` when the snapshot doesn't change #5084

Closed Andarist closed 1 month ago

Andarist commented 2 months ago

alternative to https://github.com/statelyai/xstate/pull/5080/files

changeset-bot[bot] commented 2 months ago

⚠️ No Changeset found

Latest commit: 1967780a69c3db1420efb2e601d8cc3d30ce49ac

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

davidkpiano commented 2 months ago

I think there may be a hidden problem with this logic:

const Component = (props) => {
  const items = useSelector(store, s => {
    return s.context.items.map(item => ({
      ...item,
      isSelected: props.selected === item.id
    }));
  });
}

Not the best example but the point is that if we're selecting something that mixes in data outside the snapshot (whether that's best practice or not), we may end up with stale data.

Andarist commented 2 months ago

That's a fair concern - this is how the React team has implemented' useSyncExternalStoreWithSelector', so I just used their logic here.

TkDodo commented 2 months ago

Not the best example but the point is that if we're selecting something that mixes in data outside the snapshot (whether that's best practice or not), we may end up with stale data.

Ah, I see. closing over values should still work - we could compare the selectorFn for equality but that wouldn't work with inline selectors :/

Andarist commented 2 months ago

For context, this is where the original useSyncExternalStoreWithSelector is returning early: https://github.com/facebook/react/blob/8dfbd16fce9077ab4e5fe85a7b86fa7c97a5ae04/packages/use-sync-external-store/src/useSyncExternalStoreWithSelector.js#L83-L86

davidkpiano commented 1 month ago

Closing as we went with a different approach