Functional Updates For Batching
ReactJS
Easy
5 views
Problem Description
Update state multiple times safely using functional setState.
Output Format
Render a React component.
Constraints
Use updater functions so batching still produces correct result.
Official Solution
import React, { useState } from 'react';
export default function App() {
const [n, setN] = useState(0);
function addThree() {
setN((x) => x + 1);
setN((x) => x + 1);
setN((x) => x + 1);
}
return (
<div style={{ padding: 16 }}>
<h2 style={{ marginTop: 0 }}>meetcode counter</h2>
<div style={{ fontSize: 28, fontWeight: 900 }}>{n}</div>
<div style={{ display: 'flex', gap: 10, marginTop: 10 }}>
<button type='button' onClick={addThree} style={{ padding: '10px 14px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>+3</button>
<button type='button' onClick={() => setN(0)} style={{ padding: '10px 14px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reset</button>
</div>
</div>
);
}
Solutions (0)
No solutions submitted yet. Be the first!
No comments yet. Start the discussion!