Performance: State synchronization patterns
This affects how fast the UI updates and how smoothly user interactions feel by managing state changes efficiently.
import { signal } from '@preact/signals'; const countSignal = signal(0); function ComponentA() { return <button onClick={() => countSignal.value++}>Increment</button>; } function ComponentB() { return <div>Count: {countSignal.value}</div>; }
function ComponentA() { const [count, setCount] = useState(0); return <button onClick={() => setCount(count + 1)}>Increment</button>; } function ComponentB() { const [count, setCount] = useState(0); return <div>Count: {count}</div>; }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Separate local states in multiple components | Multiple independent updates | Multiple reflows per update | High paint cost due to repeated layout | [X] Bad |
| Shared reactive state (signals or context) | Single update propagates to dependents | Single reflow per update | Lower paint cost with batched updates | [OK] Good |
count using the useState hook in Next.js?import { useState, useEffect } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setCount(c => c + 1);
}, 1000);
return () => clearInterval(timer);
}, []);
return <div>Count: {count}</div>;
}import { useState, useEffect } from 'react';
export default function DataFetcher() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(json => setData(json));
}, []);
return <div>{data.title}</div>;
}Pass the test and this pattern moves unknown