-
Notifications
You must be signed in to change notification settings - Fork 27
use lazy state initialization to avoid eager deref calculation #95
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
base: master
Are you sure you want to change the base?
Conversation
There was a problem hiding this 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! 🐎
@@ -83,9 +83,9 @@ function useStoreDependency<Props, DepType>( | |||
): DepType { | |||
enforceDispatcher(dispatcher); | |||
|
|||
const [dependencyValue, setDependencyValue] = useState({ | |||
const [dependencyValue, setDependencyValue] = useState(() => ({ |
There was a problem hiding this comment.
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)
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
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
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 <[email protected]>
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
src/GeneralStore.js
package.json
CHANGELOG.md
is up to date