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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

O-BERNARDOFOEGBU
Copy link

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

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.

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.

1 participant