Official Solution
import React, { useReducer } from 'react';
function reducer(state, action) {
switch (action.type) {
case 'inc': {
const next = state.count + 1;
return { count: next, history: [`+1 → ${next}`, ...state.history].slice(0, 5) };
}
case 'dec': {
const next = state.count - 1;
return { count: next, history: [`-1 → ${next}`, ...state.history].slice(0, 5) };
}
case 'reset':
return { count: 0, history: ['reset → 0', ...state.history].slice(0, 5) };
default:
return state;
}
}
export default function App() {
const [state, dispatch] = useReducer(reducer, { count: 0, history: [] });
return (
<div style={{ padding: 16, width: 420 }}>
<h2 style={{ marginTop: 0 }}>meetcode reducer</h2>
<div style={{ fontSize: 28, fontWeight: 800 }}>{state.count}</div>
<div style={{ display: 'flex', gap: 10, marginTop: 12 }}>
<button type='button' onClick={() => dispatch({ type: 'dec' })} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>-1</button>
<button type='button' onClick={() => dispatch({ type: 'inc' })} style={{ padding: '8px 12px', borderRadius: 12, border: 0, background: '#0b5', color: '#fff' }}>+1</button>
<button type='button' onClick={() => dispatch({ type: 'reset' })} style={{ padding: '8px 12px', borderRadius: 12, border: '1px solid #ddd', background: '#fff' }}>Reset</button>
</div>
<div style={{ marginTop: 14, color: '#555' }}>
<strong>Last actions</strong>
<ul style={{ marginTop: 6, paddingLeft: 18 }}>
{state.history.map((h, i) => <li key={i}>{h}</li>)}
</ul>
</div>
</div>
);
}
No comments yet. Start the discussion!