Independent State
Part of the Fundamentals section of Coddy's React journey — lesson 26 of 42.
Need to remember two things? Call useState twice. Each call creates a completely independent piece of state:
const [cats, setCats] = useState(0);
const [dogs, setDogs] = useState(0);Updating cats re-renders the component, but dogs keeps its value untouched. Each state has its own setter, and mixing them up is the most common beginner bug: setCats(dogs + 1) compiles fine and is still wrong.
Challenge
MediumRun the shelter's intake board: two counters that don't interfere.
- Add two states,
catsanddogs, both starting 0. - Show them in
id="cats"andid="dogs". - The
id="add-cat"button adds one cat;id="add-dog"adds one dog.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<div id="root"></div>
<script type="module" src="main.jsx"></script>
</body>
</html>This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
2JSX Expressions
Curly BracesMath in BracesBraces in AttributesCalling Functions in JSXRecap: JSX Expressions5State & Events
What Is State?Click CounterCount in StepsToggle with StateIndependent StateRecap: State & Events8Project: Profile Card
Step 1: Card StructureStep 2: Card with PropsStep 3: Like ButtonStep 4: Follow Toggle