CodeBlanks Logo Icon CodeBlanks

Boundary control

Prevent the number from going below zero.

Range clamp

A counter sometimes must stay in a range: 0–10. You use a condition inside the handler: if (count < 10) setCount(count + 1).

Or with the function form: setCount(c => Math.min(c + 1, 10)). This guarantees the limit is never crossed.

This joins logic and state; later we will see useReducer for tidier logic.

Conditional update

Inside the handler you check the range with if. If the condition fails, the updater is not called; state stays, no re-render.

This is the "ignore bad clicks" logic. Even if the user clicks, the value cannot leave the range.

This pattern is ideal for game scores, stock counts and similar bounded values.

Practice Clamped counter

Complete the skeleton. Write a ClampCounter component; import useState. Define const [count, setCount] = useState(0);. In handleUp call setCount(c => Math.min(c + 1, 10)). Return <button onClick={handleUp}>{count}</button>. Export it.

Starter code

App.jsx
import { useState } from "react";

// Define ClampCounter here

Sample solution

App.jsx
import { useState } from "react";

function ClampCounter() {
  const [count, setCount] = useState(0);
  function handleUp() { setCount(c => Math.min(c + 1, 10)); }
  return <button onClick={handleUp}>{count}</button>;
}

export default ClampCounter;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 With a limit of 10, what does Math.min(c+1, 10) do?

App.jsx
Math.min picks the smaller value.
  • Returns 11
  • Throws an error
  • Resets count
  • Never goes above 10 Correct answer

Explanation: Math.min caps the value at 10.

2 Boundary control: fill in the missing part

Question
function handleUp() { if (count < 10) ____(count + 1); }
Answer
function handleUp() { if (count < 10) setCount(count + 1); }

Explanation: You update only within the range.

3 Boundary control: match the terms

Term Meaning
Math.min Upper bound
Math.max Lower bound
if (count < 10) Condition
setCount Update

All lessons in Beginner