What will happen if you update the state directly in a React component?
Explanation:
Directly updating the state object in React won't notify the component about the change. It's crucial to use setState
(in class components) or the state updater function from useState
(in functional components) to ensure the change is detected and the component re-renders.
In React, what is the primary method for handling events in functional components?
Explanation:
Functional components in React handle events directly within the JSX using inline event handlers. You pass a function (often defined within the component) as the value to event attributes like onClick
, onChange
, etc.
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.
What is the main difference between functional components and class components in React?
Explanation:
The key difference lies in their capabilities: class components can manage state, have lifecycle methods, and inherit features, while functional components focus on rendering UI based on props.
Which of the following is a key benefit of using controlled components in React forms?
Explanation:
Controlled components excel at providing granular control over form data. By storing data in React's state, you can easily implement validation, dynamic updates, and custom form logic.
Which of the following is NOT a valid way to bind an event handler in a React class component?
Explanation:
Directly using addEventListener
to attach event listeners to DOM elements is not the recommended approach in React. React provides its own event system through Synthetic Events for better control and integration with the virtual DOM.
Which of the following JSX expressions is INVALID?
Explanation:
JSX expressions must be valid JavaScript. You cannot have an opening curly brace '{' without a corresponding closing brace '}' within a JSX expression.
What is the primary characteristic of a controlled component in React?
Explanation:
In React, controlled components store their form data within the component's state. Changes to the form input update the state, and the state updates the input's value, making React the single source of truth.
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.
How can you access the element that triggered an event within a React event handler?
Explanation:
The Synthetic Event object provided to React event handlers contains a target
property, which references the DOM element that triggered the event.