Consider this React component that reuses a button with different labels and click handlers.
function MyButton({ label, onClick }) {
return <button onClick={onClick}>{label}</button>
}
function App() {
const handleClick = () => alert('Clicked!')
return <MyButton label="Press me" onClick={handleClick} />
}What happens when the button is clicked?
function MyButton({ label, onClick }) { return <button onClick={onClick}>{label}</button> } function App() { const handleClick = () => alert('Clicked!') return <MyButton label="Press me" onClick={handleClick} /> }
Check how the onClick prop is used and what the handler does.
The MyButton component receives a function handleClick as onClick. When the button is clicked, it calls this function, which triggers an alert with 'Clicked!'.
Look at this reusable counter button component:
function CounterButton() {
const [count, setCount] = React.useState(0)
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>
}
function App() {
return <CounterButton />
}If the user clicks the button two times, what text is shown on the button?
function CounterButton() { const [count, setCount] = React.useState(0) return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button> } function App() { return <CounterButton /> }
Think about how state updates after each click.
Each click increases the count by 1. After two clicks, count is 2, so the button shows 'Clicked 2 times'.
Which of the following code snippets correctly defines a reusable React component that renders its children inside a div?
Remember how to access children passed between component tags.
Option A uses destructuring to get children from props and renders it correctly. Option C works but is less modern. Option B treats children as a direct parameter, which is incorrect. Option D references an undefined variable.
Examine this React component:
function List({ items }) {
return (
<ul>
{items.map(item => <li key={item.id}>{item.name}</li>)}
</ul>
)
}
function App() {
const data = [{ id: 1, name: 'Apple' }, { id: 2 }]
return <List items={data} />
}What error will occur when rendering App?
function List({ items }) { return ( <ul> {items.map(item => <li key={item.id}>{item.name}</li>)} </ul> ) } function App() { const data = [{ id: 1, name: 'Apple' }, { id: 2 }] return <List items={data} /> }
Check the data passed and what properties are accessed inside the map.
The second item in data lacks a 'name' property. Accessing item.name returns undefined, which React renders as empty. No TypeError occurs. Keys are unique, so no key warning. Option A is correct.
Why do reusable components help maintain a React application better?
Think about how reusing code affects changes and bugs.
Reusable components let you write code once and use it many times. This reduces repeated code and makes fixing or changing behavior easier because you update in one place. This improves maintainability. The other options are incorrect or misleading.