React / Next.js

TypeScript with React

Types for props, state, events, generics, FC type, children type, hooks typing

20 interview questionsยท
Mid-Level
1

What is the correct syntax to type React component props?

Answer

The Props interface followed by typing the function with Props as parameter is the recommended standard syntax. This approach provides excellent type inference and allows easy reuse of the Props type elsewhere in the code. It is more explicit than React.FC and provides better control over children typing.

2

How to correctly type a simple state with useState?

Answer

TypeScript automatically infers the state type from the initial value passed to useState. For a simple value like a string, there is no need to explicitly specify the generic type. Automatic inference is sufficient and makes the code more concise. Explicit typing becomes useful only for unions or when the initial value is null.

3

What is the correct type for an onClick event on a button?

Answer

React.MouseEvent<HTMLButtonElement> is the specific type for click events on a button. The generic parameter HTMLButtonElement specifies the concerned DOM element, which allows access to button-specific properties via event.currentTarget. Using native DOM MouseEvent or a too generic type would lose this typing precision.

4

What type to use for typing children of a wrapper component?

5

What is the main difference between React.FC and direct typing?

+17 interview questions

Master React / Next.js for your next interview

Access all questions, flashcards, technical tests, code review exercises and interview simulators.

Start for free