traintocode

useState() Hook in TypeScript

The useState hook is a fundamental part of React, allowing you to add state to your functional components. When using TypeScript with React, you can enhance the useState hook by providing explicit type information. This ensures that your state variables are always of the expected type, enhancing code reliability and developer experience.

In TypeScript, you specify the type of the state variable when calling useState. For example, useState<number>(0) creates a state variable with a number type, initially set to 0.

If you don't explicitly define a type, TypeScript will infer it from the initial state. However, explicitly typing the state is a good practice, especially when the initial state could be null or undefined. For instance, useState<string | null>(null) defines a state that can hold either a string or a null value.

Remember, TypeScript types should encapsulate all possible states of your component. If a state can hold multiple types (like a string, a number, or null), use a union type like useState<string | number | null>(null).

Exercise
Edit the useState() hook to allow the state to contain either a string or null, fixing the error
    You cannot do the coding exercises on this device, visit this page on a larger screen.
    App.tsx
    Loading...