React useState

Give components memory with state.

✍️ 3 exercises + code challenge in this lesson

State is data that changes over time. When state changes, React re-renders the component.

const [count, setCount] = useState(0);

  • count is the current value; setCount updates it.
  • Never change state directly; always call the setter.
  • When the new value depends on the old one, pass a function: setCount(c => c + 1).
  • For objects and arrays, create a new copy: setUser({ ...user, name: "Ali" }), setItems([...items, newItem]).

Key Takeaways: React useState

Mastering React useState helps you write clean and reliable React code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

React useState Code Example

React
<div id="root"></div>
<script src="https://unpkg.com/react@18.3.1/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@18.3.1/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/@babel/standalone@7.25.6/babel.min.js"></script>

<script type="text/babel">
const { useState, useEffect, useRef, useMemo, createContext, useContext } = React;
function Counter() {
  const [count, setCount] = useState(0);
  return (
    <div>
      <h2>{count}</h2>
      <button onClick={() => setCount(c => c - 1)}>−</button>{" "}
      <button onClick={() => setCount(c => c + 1)}>+</button>{" "}
      <button onClick={() => setCount(0)}>Reset</button>
    </div>
  );
}

function App() {
  const [dark, setDark] = useState(false);
  return (
    <div style={{ background: dark ? "#071A2F" : "white", color: dark ? "white" : "black", padding: 16 }}>
      <label><input type="checkbox" checked={dark} onChange={() => setDark(!dark)} /> Dark mode</label>
      <Counter />
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>
Free sign-in required · Google login available

React useState Practice Exercises

Check what you learned in “React useState”.

/ 3 solved
Fill in the blank

Create a state variable.

const [count, setCount] = (0);
✓ Correct! Not quite. Try again.
Multiple choice

How should you update state that depends on the previous value?

✓ Correct! Not quite. Try again.
Code challenge

Build a counter: an <h2> showing the count (starting at 5) and a "+" button that increases it. The check clicks once and expects 6.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services