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

Improve-Type-Safety-and-State-Access-in-useStateWithDeps-Hook #3027

Conversation

O-BERNARDOFOEGBU
Copy link
Contributor

This pull request aims to improve the type safety and reliability of the useStateWithDeps hook in React. Specifically, the changes address potential issues with accessing state properties using dynamic keys, ensuring that TypeScript correctly identifies and enforces the types of state properties.

Changes Implemented:
Type-Safe Iteration:

Replaced the direct for...in loop with a more type-safe iteration using Object.prototype.hasOwnProperty.call() to avoid errors related to iterating over unexpected properties.
Non-null Assertion:

Added a non-null assertion (payload[k]!) to ensure that payload[k] is not undefined when updating the state, preventing runtime issues.
Improved Type-Safe Access:

Used const k = key as keyof S to inform TypeScript that key is a valid key of S, improving the type inference and ensuring that currentState[k] and payload[k] are correctly typed.
Functional Consistency:

The changes maintain the core functionality of the hook while improving its safety and performance, ensuring that it tracks dependencies and triggers re-renders as intended.
This PR does not alter the primary behavior of the hook but makes the code more robust and type-safe, improving maintainability.

Copy link

codesandbox-ci bot commented Oct 18, 2024

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

@huozhi huozhi force-pushed the Improve-Type-Safety-and-State-Access-in-useStateWithDeps-Hook branch from 2a55931 to da30bc1 Compare December 9, 2024 23:16
@huozhi huozhi force-pushed the Improve-Type-Safety-and-State-Access-in-useStateWithDeps-Hook branch from da30bc1 to 0337802 Compare December 9, 2024 23:16
Copy link
Member

@huozhi huozhi left a comment

Choose a reason for hiding this comment

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

Thanks!

@huozhi huozhi merged commit 07d5178 into vercel:main Dec 10, 2024
7 checks passed
@O-BERNARDOFOEGBU
Copy link
Contributor Author

Thanks!

you are very welcome.

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