Coding task · JavaScript and React course · Module 3: State and Events

Practice: Counter with useState

useState is a hook that stores state: const [value, setValue] = useState(initialValue). setValue(newValue) updates the state and re-renders the component. For counters, setValue(prev => prev + 1) safely uses the previous value, and you can set the limits with e.g. Math.min(prev + 1, 100) and Math.max(prev - 1, 0).

Task

Create an oxygen counter: const [oxygen, setOxygen] = useState(21). Display the text O2 Level: {oxygen}% and add two buttons: the + button raises the level by 1 (<button onClick={() => setOxygen(prev => prev + 1)}>+</button>) and the - button lowers it by 1. The level must stay within 0-100.