Performance: State and hooks in client components
This affects interaction responsiveness and rendering speed of client components by managing state changes efficiently.
"use client"; import { useState, useRef } from 'react'; export default function Search() { const [query, setQuery] = useState(''); const timeout = useRef(null); function handleChange(e) { clearTimeout(timeout.current); const value = e.target.value; timeout.current = setTimeout(() => setQuery(value), 300); } return <input defaultValue={query} onChange={handleChange} />; }
"use client"; import { useState } from 'react'; export default function Search() { const [query, setQuery] = useState(''); return <input value={query} onChange={e => setQuery(e.target.value)} />; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| State update on every keystroke | Many small DOM updates | Triggers 1 reflow per update | High paint cost due to frequent changes | [X] Bad |
| Debounced state update | Fewer DOM updates | Single reflow after debounce | Lower paint cost | [OK] Good |
| Multiple independent state variables | Multiple updates possible | Multiple reflows if updated separately | Moderate paint cost | [!] OK |
| Combined state object | Single update per change | Single reflow | Lower paint cost | [OK] Good |
useState in a Next.js client component?useState doesuseState is a React hook that allows components to keep track of data that can change, like user input or toggles.useState helps remember and update values without reloading the page.count with initial value 0 in a Next.js client component?const [state, setState] = useState(initialValue);count starting at 0, it should be const [count, setCount] = useState(0);"use client";
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return (
setCount(count + 1)}>
Count: {count}
);
}setCount(count + 1), increasing count by 1.import { useState } from 'react';
export default function Toggle() {
const [isOn, setIsOn] = useState(false);
return (
setIsOn(!isOn)}>
{isOn ? 'ON' : 'OFF'}
);
}useState require the component to be a client component, which needs 'use client'; at the top.'use client'; at the top, so it will cause an error in Next.js.Hello, this is the message!
} </> ); } correctly includes'use client'; and uses useState to track visibility state.visible state with setVisible(!visible), and the message shows only when visible is true.Pass the test and this pattern moves unknown