Consider this React component:
function Counter() {
const [count, setCount] = React.useState(0);
return (
<button onClick={() => setCount(0)}>Count: {count}</button>
);
}What happens when the button is clicked?
function Counter() { const [count, setCount] = React.useState(0); return ( <button onClick={() => setCount(0)}>Count: {count}</button> ); }
React compares the new state value with the previous one before re-rendering.
React skips re-rendering if the new state value is strictly equal to the previous one.
Given this React component:
function Example() {
const [value, setValue] = React.useState(0);
React.useEffect(() => {
setValue(value + 1);
setValue(value + 2);
}, []);
return <div>Value: {value}</div>;
}What will be displayed after the component mounts?
function Example() { const [value, setValue] = React.useState(0); React.useEffect(() => { setValue(value + 1); setValue(value + 2); }, []); return <div>Value: {value}</div>; }
State updates inside the same event are batched and the last update wins.
Both updates use the initial value 0. The last call sets value to 2, so the final state is 2.
Which of these scenarios will cause a React functional component to re-render?
React re-renders when state changes to a new value by reference or primitive comparison.
React re-renders when setState is called with a new value that differs by reference or primitive equality. Same primitive values do not trigger re-render. Updating refs or external variables does not trigger re-render.
Which of these React state updates correctly increments a counter based on previous state?
When updating state based on previous state, use a function argument.
Option A uses the functional form of setState, which safely updates based on the latest state. Option A may cause stale updates. Option A ignores previous state argument. Option A uses invalid syntax and mutates state.
Examine this React component:
function Infinite() {
const [count, setCount] = React.useState(0);
React.useEffect(() => {
setCount(count + 1);
}, [count]);
return <div>Count: {count}</div>;
}Why does it keep re-rendering?
function Infinite() { const [count, setCount] = React.useState(0); React.useEffect(() => { setCount(count + 1); }, [count]); return <div>Count: {count}</div>; }
Check what triggers the useEffect and what it does inside.
The useEffect depends on count and updates count inside it. Each update triggers a re-render and runs useEffect again, causing an infinite loop.