Skip to content

Conversation

@aem
Copy link
Contributor

@aem aem commented Feb 18, 2021

h/t @gmcnaughton for pointing out that we can optimize this hook with a lazy state init to avoid double-calculating the deref on every render, which can be meaningful for expensive derefs

TODOs

  • linter, checker, and test are passing
  • any new public modules are exported from src/GeneralStore.js
  • version numbers are up to date in package.json
  • CHANGELOG.md is up to date

Copy link
Contributor

@gmcnaughton gmcnaughton left a comment

Choose a reason for hiding this comment

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

Thanks for the speedup! 🐎

enforceDispatcher(dispatcher);

const [dependencyValue, setDependencyValue] = useState({
const [dependencyValue, setDependencyValue] = useState(() => ({
Copy link
Contributor

Choose a reason for hiding this comment

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

This is 💯 !

The only other tweak we could consider is literally moving the const newValue = { dependency: ... } up above here, then reusing newValue both as the initial state and where it is already used. That has the added benefit of skipping an extra eval of the deref in the opposite case (where we are initializing state for the first time)

gmcnaughton added a commit to gmcnaughton/general-store that referenced this pull request Feb 19, 2021
See HubSpot#95

Avoids duplicate deref calculations in `useStoreDependency`. Only
calculate once; use this result to initialize state (if necessary)
and as the next state.

When the value changes, two deref calculations will still run:

1. the initial render/hook call
2. the re-render/hook call triggered by setting the new value in state
gmcnaughton added a commit to gmcnaughton/general-store that referenced this pull request Mar 15, 2021
See HubSpot#95

Avoids duplicate deref calculations in `useStoreDependency`. Only
calculate once; use this result to initialize state (if necessary)
and as the next state.

When the value changes, two deref calculations will still run:

1. the initial render/hook call
2. the re-render/hook call triggered by setting the new value in state
aem pushed a commit that referenced this pull request Mar 15, 2021
See #95

Avoids duplicate deref calculations in `useStoreDependency`. Only
calculate once; use this result to initialize state (if necessary)
and as the next state.

When the value changes, two deref calculations will still run:

1. the initial render/hook call
2. the re-render/hook call triggered by setting the new value in state

Co-authored-by: Gordon McNaughton <gmcnaughton@hubspot.com>
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.

3 participants