In a class component, how do you update the state?
Explanation:
In React class components, you should never mutate this.state
directly. Instead, use this.setState()
. This method updates the state and informs React to re-render the component and its children if necessary.
In React functional components, how do you typically handle events?
Explanation:
Functional components in React handle events directly within the JSX. You can define functions inline or pass function references as event handlers to JSX elements.
How can you access the original DOM event object in a React event handler?
Explanation:
While the synthetic event object is often sufficient, you can access the underlying native DOM event through event.nativeEvent
. This allows interaction with specific DOM APIs if needed.
What happens if a prop is not provided to a component with a default prop defined?
Explanation:
Default props act as fallback values when a prop is not explicitly passed to the component.
Why is event binding often necessary in class components?
Explanation:
In JavaScript, this
can be tricky, especially within class methods. Binding event handlers ensures that this
refers to the component instance when the handler is executed, allowing access to component methods and properties.
What's a common way to bind event handlers in React class components?
Explanation:
Two common approaches to bind event handlers are: 1) using this.handleClick = this.handleClick.bind(this)
in the constructor or 2) using arrow functions directly in the render
method, which lexically scope this
.
How can you display validation errors to the user in a React form?
Explanation:
A common approach is to conditionally render error messages in your component's JSX. After validating input, you can update the component's state with error information and use it to control the display of error messages.
How do class components in React typically handle events?
Explanation:
Class components handle events by defining methods that serve as event handlers. These methods are then bound to event attributes in the JSX, usually within the render
method.
What are props in React?
Explanation:
Props allow data to be passed down from parent components to child components, making them customizable and reusable.
What is the second argument of the useEffect
Hook used for?
Explanation:
The second argument to useEffect
is an array of dependencies. If any of these dependencies change between renders, the effect will run again. An empty array ([]) means the effect only runs once, after the initial render.