Setting Initial State with a Value
What you'll learn: How to give your state variable a starting value when your component first appears on screen.
The Core Idea
When you call useState, you pass an argument inside the parentheses — this is your initial state value. React uses this value the very first time your component renders (mounts), and only that first time.
Think of it like setting the default position on a thermostat when you first install it. You might set it to 68°F initially, but users can change it later. That starting value only matters once — when the thermostat powers on.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // 0 is the initial value
return <div>Count: {count}</div>;
}
The 0 inside useState(0) tells React: "The first time this component renders, count should be 0." After that, React remembers whatever value you've set using setCount.
Initial Values for Different Types
You can pass any JavaScript value as initial state:
const [isOpen, setIsOpen] = useState(false); // boolean
const [name, setName] = useState(''); // string
const [age, setAge] = useState(21); // number
const [user, setUser] = useState(null); // null
The type of value you pass determines what kind of data your state holds. Start with false for toggles, empty strings for text, 0 for counters, or null for data that hasn't loaded yet.
When Initial State Matters
Initial state is set only on mount — when the component first appears. If your component unmounts and remounts later, it gets the initial value again. But between re-renders (while it stays mounted), React ignores the initial value and remembers the current state.
Key Takeaway: Pass a value directly to useState(value) to set what your state should be the very first time your component renders — this initialization happens once, on mount.