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

Reduce re-renders by auto detecting state dependencies #186

Merged
merged 6 commits into from
Dec 28, 2019

Conversation

shuding
Copy link
Member

@shuding shuding commented Dec 8, 2019

By moving data, error, isValidating away from the state (useReducer) to a ref (stateRef), the hook won't trigger another re-render anymore when one of these values updates.

Instead, we add getters to these values (implemented with defineProperties). Once a value is read, it will be marked as a dependency immediately. Thus, we can trigger a re-render if any dependency changes in the future.

With this change, useSWR will never cause unnecessary re-renders:

const { data } = useSWR(...)
// will not re-render if `isValidating` or `error` changes

No changes needed from the user side (and Suspense mode is not affected).

Fixes #184. Related #144, #114.

Published at swr@0.1.13-beta.0 swr@0.1.15-beta.0.


This PR has been running on our production for a couple of weeks, and it works very well 🎉

@shuding
Copy link
Member Author

shuding commented Dec 26, 2019

Added more code optimization (memorize returned state and dispatch function), also fixed a bug causing SWRPages not updating in 5795f33.

Published a new version based on the current master to swr@0.1.15-beta.0.

@shuding
Copy link
Member Author

shuding commented Dec 26, 2019

Note: in the future we are going to simplify the useSWRPages hook (which is undocumented currently).

@shuding shuding removed the on hold label Dec 27, 2019
@shuding shuding merged commit 994806e into master Dec 28, 2019
@shuding shuding deleted the state-optimization branch December 28, 2019 02:04
@iamstarkov
Copy link

Seems like this PR breaks ssr when initialData is used. see #230

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.

Performance: Component Re-rendered because of hook changes.
2 participants