JavaScript and React course ยท Module 3: State and Events
Component State (State)
In this lesson6
On a cosmic journey through the React galaxy, state is like the rocket fuel powering the interactivity of your components. Without state, components would be static objects - like planets without an atmosphere. State allows components to "remember" information and react to changes, making your applications alive and responsive.
What is component state?
State is data (a number, text, a boolean, an array or an object) that a component remembers between renders. Unlike props, which the parent passes to the component, state belongs to the component itself and only the component can change it - always through its setter function, e.g. setFuel, never by modifying it directly.
Imagine a spaceship control panel. Props are like set destination coordinates - you cannot change them from the panel level. State, on the other hand, is like the current speed, altitude, and temperature readings - data that constantly changes and is controlled by the panel itself.
Managing state in functional components
In modern React, state in functional components is managed using the useState hook. This simple yet powerful hook allows you to add state to functional components.
Basic useState syntax
import React, { useState } from 'react';
function ControlPanel() {
// Declaring a state variable "fuel" with initial value 100
const [fuel, setFuel] = useState(100);
// fuel - the current state value
// setFuel - the function to update state
return (
<div className="control-panel">
<h2>Control Panel</h2>
<p>Fuel Level: {fuel}%</p>
<button onClick={() => setFuel(fuel - 10)}>
Use Fuel
</button>
</div>
);
}In the example above:
- We import the
useStatehook from React - We call
useState(100)to create a state variablefuelwith an initial value of 100 - We destructure the result to get:
fuel: the current state valuesetFuel: the function to update that value
- We use
setFuelin the click event handler to decrease the fuel value by 10
Using multiple state variables
A component can have multiple independent state variables:
function SpaceshipDashboard() {
const [fuel, setFuel] = useState(100);
const [speed, setSpeed] = useState(0);
const [shields, setShields] = useState(true);
const [destination, setDestination] = useState('Orbit');
return (
<div className="dashboard">
<h2>Spaceship Dashboard</h2>
<div className="gauges">
<div className="gauge">
<h3>Fuel</h3>
<p>{fuel}%</p>
<button onClick={() => setFuel(Math.max(0, fuel - 5))}>
Increase Thrust
</button>
</div>
<div className="gauge">
<h3>Speed</h3>
<p>{speed} km/s</p>
<button onClick={() => setSpeed(speed + 1)}>
Accelerate
</button>
<button onClick={() => setSpeed(Math.max(0, speed - 1))}>
Decelerate
</button>
</div>
<div className="gauge">
<h3>Shields</h3>
<p>{shields ? 'Enabled' : 'Disabled'}</p>
<button onClick={() => setShields(!shields)}>
Toggle
</button>
</div>
<div className="gauge">
<h3>Destination</h3>
<p>{destination}</p>
<select
value={destination}
onChange={(e) => setDestination(e.target.value)}
>
<option value="Orbit">Earth Orbit</option>
<option value="Moon">Moon</option>
<option value="Mars">Mars</option>
<option value="Asteroid Belt">Asteroid Belt</option>
</select>
</div>
</div>
</div>
);
}Complex state structures
State can be a simple value (number, string, boolean), but it can also be a more complex structure, like an array or object:
function CrewManagement() {
const [crew, setCrew] = useState([
{ id: 1, name: 'Anna Nowak', role: 'Captain', onDuty: true },
{ id: 2, name: 'Jan Kowalski', role: 'Navigator', onDuty: false },
{ id: 3, name: 'Maria Wisniewska', role: 'Engineer', onDuty: true }
]);
const toggleDuty = (crewId) => {
setCrew(crew.map(member =>
member.id === crewId
? { ...member, onDuty: !member.onDuty }
: member
));
};
return (
<div className="crew-management">
<h2>Crew Management</h2>
<ul className="crew-list">
{crew.map(member => (
<li key={member.id} className={member.onDuty ? 'on-duty' : 'off-duty'}>
<strong>{member.name}</strong> - {member.role}
<button onClick={() => toggleDuty(member.id)}>
{member.onDuty ? 'End Shift' : 'Start Shift'}
</button>
</li>
))}
</ul>
</div>
);
}In this example, the crew state is an array of objects. The toggleDuty function uses map to create a new array with the updated state of a specific crew member.
State as a snapshot
In React, state works like a snapshot. When React renders a component, it "captures" the state at that point in time, and all values inside the rendering function (including event handlers) will "see" the same state snapshot.
Consider this example:
function RocketLauncher() {
const [countdown, setCountdown] = useState(10);
const decrementCountdown = () => {
// This will NOT work as expected if we want to
// perform multiple decrements in a single render cycle
setCountdown(countdown - 1); // Uses the same value from the snapshot
setCountdown(countdown - 1); // Still uses the same value!
};
return (
<div className="rocket-launcher">
<h2>Countdown to Launch: {countdown}</h2>
<button onClick={decrementCountdown}>
Decrease Countdown
</button>
</div>
);
}In the example above, despite calling setCountdown twice, the value will only decrease by 1, not by 2. This happens because both updates "see" the same countdown value from the snapshot.
Updating state based on previous state
To solve the snapshot problem, React allows you to pass a function to the state updater function. This function receives the previous state as an argument:
function RocketLauncher() {
const [countdown, setCountdown] = useState(10);
const decrementCountdown = () => {
// This will work correctly, even for multiple updates
setCountdown(prevCount => prevCount - 1); // Based on the previous value
setCountdown(prevCount => prevCount - 1); // Based on the result of the previous update
};
return (
<div className="rocket-launcher">
<h2>Countdown to Launch: {countdown}</h2>
<button onClick={decrementCountdown}>
Decrease Countdown
</button>
</div>
);
}Now, with each button click, the countdown will decrease by 2.
Updating objects in state
When updating objects in state, it is important to always create a new object rather than modifying the existing one. This is in line with the immutability principles in React:
function SpaceshipSystems() {
const [systems, setSystems] = useState({
engines: 'offline',
lifeSupportOutput: 100,
navigationStatus: 'calibrating',
shields: 85
});
const startEngines = () => {
// WRONG - modifying the original object
// systems.engines = 'online';
// setSystems(systems);
// CORRECT - creating a new object
setSystems({
...systems, // copies all existing properties
engines: 'online' // overrides only the one we want to change
});
};
return (
<div className="spaceship-systems">
<h2>Systems Status</h2>
<p>Engines: {systems.engines}</p>
<p>Life Support: {systems.lifeSupportOutput}%</p>
<p>Navigation: {systems.navigationStatus}</p>
<p>Shields: {systems.shields}%</p>
<button onClick={startEngines}>
Start Engines
</button>
</div>
);
}Updating arrays in state
Just like with objects, when updating arrays you must also follow immutability principles:
function MissionLog() {
const [logs, setLogs] = useState([
{ id: 1, time: '08:00', message: 'Mission started' }
]);
const addLog = () => {
const newLog = {
id: Math.max(0, ...logs.map(log => log.id)) + 1, // highest id + 1, so it never repeats after a removal
time: new Date().toLocaleTimeString(),
message: 'New log entry'
};
// WRONG - mutating the original array
// logs.push(newLog);
// setLogs(logs);
// CORRECT - creating a new array
setLogs([...logs, newLog]); // adding to the end
// or
// setLogs([newLog, ...logs]); // adding to the beginning
};
const removeLog = (logId) => {
// Filtering - creating a new array without the removed element
setLogs(logs.filter(log => log.id !== logId));
};
return (
<div className="mission-log">
<h2>Mission Log</h2>
<button onClick={addLog}>Add New Entry</button>
<ul className="log-entries">
{logs.map(log => (
<li key={log.id}>
<span className="time">{log.time}</span>
<span className="message">{log.message}</span>
<button onClick={() => removeLog(log.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
}You can see the same array operations - adding, toggling and removing an entry - in action in the demo below, together with a counter (a number), a switch (a boolean) and a text field (text). Look at the box at the bottom: we call useState only at the top level of a component, never inside a loop, a condition or a nested function, because React tells the states apart by the order of the calls on every render.
Code for this lesson: App.jsx
import React, { useState } from 'react';
// Simple counter - the basics of useState
function SimpleCounter() {
const [count, setCount] = useState(0);
return (
<div style={{
backgroundColor: '#252545',
padding: '20px',
borderRadius: '12px',
textAlign: 'center'
}}>
<h3 style={{ color: '#00d4ff', marginTop: 0 }}>Simple Counter</h3>
<div style={{
fontSize: '48px',
fontWeight: 'bold',
margin: '20px 0',
color: count > 0 ? '#4caf50' : count < 0 ? '#f44336' : 'white'
}}>
{count}
</div>
<div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
<button
onClick={() => setCount(count - 1)}
style={{
padding: '10px 20px',
backgroundColor: '#f44336',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '18px'
}}
>
-1
</button>
<button
onClick={() => setCount(0)}
style={{
padding: '10px 20px',
backgroundColor: '#666',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
Reset
</button>
<button
onClick={() => setCount(count + 1)}
style={{
padding: '10px 20px',
backgroundColor: '#4caf50',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer',
fontSize: '18px'
}}
>
+1
</button>
</div>
</div>
);
}
// Toggle - boolean state
function ToggleSwitch() {
const [isOn, setIsOn] = useState(false);
return (
<div style={{
backgroundColor: '#252545',
padding: '20px',
borderRadius: '12px',
textAlign: 'center'
}}>
<h3 style={{ color: '#00d4ff', marginTop: 0 }}>Toggle Switch</h3>
<div
onClick={() => setIsOn(!isOn)}
style={{
width: '80px',
height: '40px',
backgroundColor: isOn ? '#4caf50' : '#666',
borderRadius: '20px',
cursor: 'pointer',
position: 'relative',
margin: '20px auto',
transition: 'background-color 0.3s'
}}
>
<div style={{
width: '32px',
height: '32px',
backgroundColor: 'white',
borderRadius: '50%',
position: 'absolute',
top: '4px',
left: isOn ? '44px' : '4px',
transition: 'left 0.3s'
}} />
</div>
<p style={{ color: '#ccc' }}>
Status: <strong style={{ color: isOn ? '#4caf50' : '#f44336' }}>
{isOn ? 'ON' : 'OFF'}
</strong>
</p>
</div>
);
}
// Form - string state
function TextInput() {
const [text, setText] = useState('');
return (
<div style={{
backgroundColor: '#252545',
padding: '20px',
borderRadius: '12px'
}}>
<h3 style={{ color: '#00d4ff', marginTop: 0 }}>Text Field</h3>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Type something..."
style={{
width: '100%',
padding: '12px 15px',
border: '2px solid #444',
borderRadius: '8px',
backgroundColor: '#1a1a2e',
color: 'white',
fontSize: '16px',
boxSizing: 'border-box'
}}
/>
<p style={{ color: '#888', marginBottom: 0 }}>
Typed: <strong style={{ color: 'white' }}>{text || '(empty)'}</strong>
{' '}({text.length} characters)
</p>
</div>
);
}
// List - array state
function TodoList() {
const [todos, setTodos] = useState([
{ id: 1, text: 'Learn React', done: true },
{ id: 2, text: 'Understand useState', done: false },
{ id: 3, text: 'Create a project', done: false }
]);
const [newTodo, setNewTodo] = useState('');
const addTodo = () => {
if (newTodo.trim()) {
setTodos([...todos, {
id: Date.now(),
text: newTodo,
done: false
}]);
setNewTodo('');
}
};
const toggleTodo = (id) => {
setTodos(todos.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
));
};
const deleteTodo = (id) => {
setTodos(todos.filter(todo => todo.id !== id));
};
return (
<div style={{
backgroundColor: '#252545',
padding: '20px',
borderRadius: '12px'
}}>
<h3 style={{ color: '#00d4ff', marginTop: 0 }}>Task List</h3>
<div style={{ display: 'flex', gap: '10px', marginBottom: '15px' }}>
<input
type="text"
value={newTodo}
onChange={(e) => setNewTodo(e.target.value)}
onKeyDown={(e) => e.key === 'Enter' && addTodo()}
placeholder="New task..."
style={{
flex: 1,
padding: '10px 15px',
border: '2px solid #444',
borderRadius: '8px',
backgroundColor: '#1a1a2e',
color: 'white'
}}
/>
<button
onClick={addTodo}
style={{
padding: '10px 20px',
backgroundColor: '#4caf50',
color: 'white',
border: 'none',
borderRadius: '8px',
cursor: 'pointer'
}}
>
Add
</button>
</div>
<div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
{todos.map(todo => (
<div key={todo.id} style={{
display: 'flex',
alignItems: 'center',
gap: '10px',
padding: '10px 15px',
backgroundColor: '#1a1a2e',
borderRadius: '8px'
}}>
<input
type="checkbox"
checked={todo.done}
onChange={() => toggleTodo(todo.id)}
style={{ width: '20px', height: '20px', cursor: 'pointer' }}
/>
<span style={{
flex: 1,
textDecoration: todo.done ? 'line-through' : 'none',
color: todo.done ? '#666' : 'white'
}}>
{todo.text}
</span>
<button
onClick={() => deleteTodo(todo.id)}
style={{
padding: '5px 10px',
backgroundColor: '#f44336',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: 'pointer'
}}
>
ร
</button>
</div>
))}
</div>
<p style={{ color: '#888', marginBottom: 0, marginTop: '10px' }}>
Completed: {todos.filter(t => t.done).length} / {todos.length}
</p>
</div>
);
}
export default function App() {
return (
<div style={{
fontFamily: 'Arial, sans-serif',
backgroundColor: '#0a0a1a',
minHeight: '100vh',
padding: '20px',
color: 'white'
}}>
<header style={{
textAlign: 'center',
marginBottom: '30px',
padding: '30px',
background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
borderRadius: '16px'
}}>
<h1 style={{ margin: 0 }}>useState in React</h1>
<p style={{ margin: '10px 0 0 0', opacity: 0.9 }}>
Managing component state
</p>
</header>
<div style={{
display: 'grid',
gridTemplateColumns: 'repeat(auto-fit, minmax(300px, 1fr))',
gap: '20px'
}}>
<SimpleCounter />
<ToggleSwitch />
<TextInput />
<TodoList />
</div>
<div style={{
backgroundColor: '#1a1a2e',
padding: '20px',
borderRadius: '12px',
marginTop: '30px'
}}>
<h3 style={{ color: '#ff9800', marginTop: 0 }}>useState Rules:</h3>
<ul style={{ color: '#ccc', lineHeight: '1.8', paddingLeft: '20px' }}>
<li>Only call it at the <strong>top level</strong> of a component</li>
<li>Do not use it inside loops, conditions, or nested functions</li>
<li>Updating state triggers a <strong>re-render</strong></li>
<li>State is <strong>isolated</strong> for each component instance</li>
</ul>
</div>
</div>
);
}Each of the four panels has its own independent state: clicking the counter does not change the task list, because every component keeps its state separately.
When to use state?
State should be used for data that:
- Changes over time
- Affects the rendering of the component
- Cannot be computed from props or other state
Not all data should be in state. Good questions to ask yourself:
- Does the data come from a parent via props? If so, it probably should not be in state.
- Does the data remain unchanged over time? If so, it probably should not be in state.
- Can the data be computed from existing props or state? If so, it definitely should not be in state.
Summary
State is a key element of React components that allows you to:
- Store data specific to the component
- Manage data that changes over time
- Create interactive user interfaces that respond to user actions
In the following sections, we will see how to handle events in React and how to combine them with state management to create fully interactive applications.
Code for this lesson: App.jsx
import React, { useState } from 'react';
function ControlPanel() {
const [fuel, setFuel] = useState(100);
const [speed, setSpeed] = useState(0);
const [shields, setShields] = useState(true);
return (
<div className="control-panel">
<h1>Spaceship control panel</h1>
<div className="gauges">
<div className="gauge">
<h3>Fuel</h3>
<div className="progress-bar">
<div
className="progress-fill fuel"
style={{ width: `${fuel}%` }}
>
{fuel}%
</div>
</div>
<button
onClick={() => setFuel(Math.max(0, fuel - 10))}
disabled={fuel <= 0}
>
Increase thrust (-10% fuel)
</button>
</div>
<div className="gauge">
<h3>Speed</h3>
<p className="speed-display">{speed} km/s</p>
<div className="speed-controls">
<button onClick={() => setSpeed(speed + 1)}>
Accelerate (+1)
</button>
<button
onClick={() => setSpeed(Math.max(0, speed - 1))}
disabled={speed <= 0}
>
Slow down (-1)
</button>
</div>
</div>
<div className="gauge">
<h3>Shields</h3>
<p className={`shield-status ${shields ? 'active' : 'inactive'}`}>
{shields ? 'On' : 'Off'}
</p>
<button onClick={() => setShields(!shields)}>
{shields ? 'Turn off shields' : 'Turn on shields'}
</button>
</div>
</div>
</div>
);
}
function App() {
return (
<div className="app">
<ControlPanel />
</div>
);
}
export default App;Docs entries used in this lesson
Spotted a mistake in this lesson?
Hands-on tasks in the game
- Horizontal ordering
Arrange the syntax for declaring state using useState: