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: optimise component performance with useRef #5749

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

vismay7
Copy link

@vismay7 vismay7 commented Sep 16, 2024

  • Performance optimization: By using useRef instead of useState, unnecessary re-renders are avoided, leading to better performance.

  • Corrected example: A bug in the example code has been fixed, ensuring that props are passed correctly.

@KevinVandy
Copy link
Member

This change has already been made in the alpha branch for v9, so check that out.

But does it actually avoid unnecessary rerenders? We never call a set state for it. I think the 2 approaches are actually identical.

@vismay7
Copy link
Author

vismay7 commented Sep 17, 2024

I agree with your answer but i just wanted to cross check with you as my intention of using useRef() here is to render directly from DOM itself as we are not updating any current value, so if we use setState() the set function schedules an update to component's state and then applied to state change so my purpose is to make it more faster where it reacts itself in DOM loading if we use useRef()

can you add up if there is any thing i am missing so that I can correct it

@KevinVandy
Copy link
Member

We are only using the state initializer though. The set state here isn't even defined in the tuple, so it won't get used.

@vismay7
Copy link
Author

vismay7 commented Sep 18, 2024

I agree that we're only using the state initializer and not the setter function, which indeed won't cause any re-renders.

However, I believe in this particular case, switching from useState to useRef could be beneficial. Since useRef persists the value across renders without triggering a re-render when updated, it seems more suitable here. If we don't need the component to re-render on value change and only need to store a mutable value across renders, useRef is a better fit. which could slightly improve performance, especially in components where performance is a concern.

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.

2 participants