import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter;
The component initializes count to 0. It renders the count and a button. Clicking the button calls setCount(count + 1), which updates the state and causes re-render with incremented count.
Option A correctly defines a functional component using an arrow function that returns JSX directly. Option D is also valid and correctly returns JSX. Option B misses return statement. Option C misses return statement.
import React, { useEffect } from 'react'; function Example() { useEffect(() => { console.log('Effect ran'); }, []); return <div>Check console</div>; } export default Example;
When the dependency array is empty, useEffect runs its effect only once after the component mounts (first render). It does not run on subsequent renders.
import React, { useState } from 'react'; function Toggle() { const [isOn, setIsOn] = useState(false) return ( <button onClick={setIsOn(!isOn)}> {isOn ? 'ON' : 'OFF'} </button> ); } export default Toggle;
The onClick handler is set to the result of calling setIsOn(!isOn) immediately during render, causing an error. It should be a function that calls setIsOn when clicked.
import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); function handleClick() { setCount(count + 1); setCount(count + 1); } return ( <div> <p>Count: {count}</p> <button onClick={handleClick}>Increment Twice</button> </div> ); } export default Counter;
Both setCount calls use the same stale value of count (0), so both set count to 1. The final state after both calls is 1, not 2.