Up until this point, the components we've created have been stateless. They have properties (aka props) that are passed in from their parent, but nothing changes about them once the components show up on the screen. A component can't change its own props. For many interactive scenarios, you don't want that. You want to be able to change aspects of your components as a result of some user interaction (or some data getting returned from a server or a billion other things!)
What we need is another way to store data on a component that goes beyond props. We need a way to store data that can be changed, and we need React to update what we see on the screen whenever that data changes. What we need is something known as state! In the previous tutorial, we learned that function components get access to React features such as state by calling hooks. The hook for state is called useState, and in this tutorial we are going to learn all about it and how you can use it to create stateful components.
Onwards!
OMG! A React Book Written by Kirupa?!!
To kick your React skills up a few notches, everything you see here and more (with all its casual clarity!) is available in both paperback and digital editions.
BUY ON AMAZONUsing State
If you know how to work with props, you totally know how to work with state...sort of. There are some differences, but they are too subtle to bore you with right now. Instead, let's just jump right in and see state in action by using it in a small example.
What we are going to do is create a simple lightning counter example:

What this example does is nothing crazy. Lightning strikes the earth quite often, and a number you will see quoted is about 100 times a second. We have a counter that increments the number you see by that same amount every second. Let's create it.
Our Starting Point
The primary focus of this example is to see how we can work with state. There is no point in us spending a bunch of time creating the example from scratch and retracing paths that we've walked many times already. That's not the best use of anybody's time.
Instead of starting from scratch, use the Vite project you created in Easily Set Up Your React Dev Environment (or create a brand new one). Open the src/App.jsx file, delete everything in it, and replace it with the following:
function LightningCounter() {
return <h1>Hello!</h1>;
}
function LightningCounterDisplay() {
const divStyle = {
width: 250,
textAlign: "center",
backgroundColor: "black",
padding: 40,
fontFamily: "sans-serif",
color: "#999",
borderRadius: 10
};
return (
<div style={divStyle}>
<LightningCounter />
</div>
);
}
export default LightningCounterDisplay;
We also need to clear out the styling that the Vite template gives us by default. Open src/index.css and delete everything in it. You can leave the file itself in place, for main.jsx imports it.
The bulk of this code is the divStyle object that contains the styling information responsible for the cool rounded background. The LightningCounterDisplay component returns a div element that wraps the LightningCounter component.
The LightningCounter component is where all the action is going to be taking place:
function LightningCounter() {
return <h1>Hello!</h1>;
}
This component, as it is right now, has nothing interesting going for it. It just returns the word Hello! That's OK - we'll fix this component up later.
The last thing to look at is something you don't need to touch. Your src/main.jsx file already takes our default export (which it imports as App) and renders it inside the root element in index.html using createRoot. That's pretty much it. When you run npm run dev and open the page Vite gives you, you should see the word Hello! inside a black rounded rectangle.
Getting Our Counter On
Now that we have an idea of what we are starting with, it's time to make plans for our next steps. The way our counter works is pretty simple. We are going to be using a setInterval function that calls some code every 1000 milliseconds (aka 1 second). That "some code" is going to increment a value by 100 each time it is called. Seems pretty straightforward, right?
To make this all work, we are going to be relying on two hooks:
- useState
This hook lets our component remember a value between renders, and it tells React to update the screen whenever that value changes. This is the star of this tutorial. - useEffect
This hook lets us run some code just after our component has been displayed on the screen. We'll use it to start our timer. It's a big topic, so we'll look at it in detail in the next tutorial. For now, I'll just show you the bare minimum we need.
We'll see these hooks in use shortly, but I wanted to give you a preview of them so that you can spot them easily in a lineup!
Setting the Initial State Value
We need a variable to act as our counter, and let's call this variable strikes. There are a bunch of ways to create this variable. The most obvious one is the following:
let strikes = 0; // :P
We don't want to do that, though. React calls our LightningCounter function every time it needs to figure out what our component should look like. Each of those calls starts with a clean slate, so our strikes variable would go right back to 0 every time. On top of that, changing a regular variable doesn't tell React that anything needs to be redrawn. What we want is a variable that React remembers for us and watches. That's what useState gives us. Add the following highlighted lines to our LightningCounter component:
import { useState } from "react";
function LightningCounter() {
const [strikes, setStrikes] = useState(0);
return <h1>{strikes}</h1>;
}
The import line goes at the very top of App.jsx, above everything else in the file. The line that does all the work is this one:
const [strikes, setStrikes] = useState(0);
When you call useState, you give it an initial value (0 in our case). What you get back is an array with exactly two things in it: the current value of your state, and a function for updating that value. We use array destructuring to give those two things names. The names are up to you, but the convention is to name the first one after the thing it holds (strikes) and the second one the same name prefixed with set (setStrikes).
That initial value only matters the very first time our component renders. On every render after that, React ignores it and hands us whatever value it currently has stored. Where does React keep all of this? It remembers it for us, behind the scenes, keyed to our component and to the order in which we called our hooks. We'll look at why that order matters in the Meet React Hooks tutorial.
Going back to our code, the h1 now displays the value stored by strikes instead of our default Hello! text. If you preview your example in the browser, you will see a value of 0 displayed. That's a start! We aren't using setStrikes yet, so your editor (or linter) may grumble about an unused variable. That's about to be fixed.
Starting Our Timer & Setting State
Next up is getting our timer going and incrementing our strikes value. Like we mentioned earlier, we will be using the setInterval function to increase strikes by 100 every second. We are going to start that timer right after our component has been displayed, and for that we'll use useEffect.
Make the following highlighted changes to our LightningCounter component:
import { useState, useEffect } from "react";
function LightningCounter() {
const [strikes, setStrikes] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setStrikes((prevStrikes) => prevStrikes + 100);
}, 1000);
return () => clearInterval(timer);
}, []);
return <h1>{strikes}</h1>;
}
There is a lot going on here, so let's go through it slowly. The useEffect hook takes a function that React will run after our component has been displayed. Inside that function, we call setInterval to call our own little function every 1000 milliseconds. All that our little function does is call setStrikes, the function we got back from useState, to change our state.
The function we hand to setStrikes is the interesting part:
setStrikes((prevStrikes) => prevStrikes + 100);
Instead of giving setStrikes a new value, we gave it a function. React calls that function with whatever the latest value of strikes is, and whatever we return becomes the new value. In our case, we return the old value plus 100. You are probably wondering why we didn't just write setStrikes(strikes + 100). That is a really good question, and we'll answer it in a few moments when we talk about snapshots.
The two other things in the useEffect call are the return () => clearInterval(timer) line and the empty array ([]) at the end. The first one is a clean-up function that React calls when our component goes away, so that our timer doesn't keep running forever. The second one tells React to run our effect just once, after the component first shows up. Both of these are important, and the Effects with useEffect tutorial explains each of them in all their glory. If you skipped the clean-up function, our app would still run in production. In development, React's Strict Mode (which our Vite project turns on in main.jsx) deliberately starts our effect, cleans it up, and starts it again to make sure we cleaned up properly. Without the clean-up, we would have two timers going, and our counter would count at 200 per second!
Rendering the State Change
If you preview your app now, you'll see our strikes value start to increment by 100 every second:

Let's ignore for a moment what happens with our code. That is pretty straightforward. The interesting thing is how everything we've done ends up updating what you see on the screen. That updating has to do with this React behavior: Whenever you call a state setter function like setStrikes with a new value, React calls your component function again. This second (or third or ten thousandth) call returns fresh JSX that reflects the new state, React compares that JSX to what is currently on the screen, and it updates only the parts of the DOM that are different. If other components are affected, they get called again as well. The end result of all this is that what you see on your screen is the latest representation of your app's state. Keeping your data and UI in sync is one of the hardest problems with UI development, so it's nice that React takes care of this for us. It makes all of this pain of learning to use React totally worth it...almost! :P
Re-running a component is what React calls rendering. When someone says that a component "re-renders", they just mean that React called its function again. We'll spend a whole lot more time on this in the lifecycle tutorial.
State Is a Snapshot
Now, back to that question from earlier. Why did we write setStrikes((prevStrikes) => prevStrikes + 100) instead of the more obvious setStrikes(strikes + 100)? To answer this, we need to talk about something that surprises just about everyone the first time they see it: the value of a state variable is fixed for the entire duration of a single render.
When React calls our component function, it hands us the current state values. Our strikes variable is a plain old constant for that one call. Calling setStrikes doesn't change that constant. All it does is ask React to call our component function again with a new value. Anything that was created during the first call (event handlers, timers, effects) still sees the old value. In other words, each render gets its own snapshot of our state.
To see the effects of this, let's look at a button that is supposed to add 3 to a counter:
function AddThree() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
return (
<button onClick={addThree}>{count}</button>
);
}
If you click this button, the count goes up by 1, not 3. Inside this particular render, count is 0. We told React to set the count to 0 + 1 three times in a row. React isn't confused. We asked it to do exactly that!
To fix this, we use the function form of the state setter. This is known as a functional update:
function AddThree() {
const [count, setCount] = useState(0);
function addThree() {
setCount((c) => c + 1);
setCount((c) => c + 1);
setCount((c) => c + 1);
}
return (
<button onClick={addThree}>{count}</button>
);
}
React puts each of those functions in a queue. When it is time to render, React runs them one after another, passing the result of one into the next. We start with 0, then 1, then 2, and end up with 3. This time, a click really does add 3.
This same snapshot behavior is what would have bitten our lightning counter. Our effect only runs once, so the setInterval callback was created during the very first render where strikes was 0. That callback keeps living for as long as the timer is running, and it will always see strikes as 0. If we had written setStrikes(strikes + 100), every tick would have set our state to 100, and our counter would get stuck there. The functional update doesn't care about what the stale variable says. It asks React for the latest value.
The rule of thumb is simple. If your new state is calculated from the previous state, use the functional form. If your new state doesn't depend on the old state at all (like setName("Batman")), just pass the value directly. As a bonus, a linter will often warn you when you are about to get this wrong. Vite's default linting setup flags the mistaken version of our counter with a warning about a missing dependency, which will make a lot more sense after the next tutorial.
Objects and Arrays as State
So far, our state has been a single number. State can hold any JavaScript value you want, including objects and arrays. There is one rule you need to follow when you do this: treat state as read-only. You don't change an object or an array that is stored in state. You make a new one with the changes you want and hand that to the setter function.
Why? When you call a state setter, React compares the new value to the old one to figure out if anything changed. For objects and arrays, it checks whether they are the exact same object in memory, not whether their contents look the same. If you modify an object and pass that same object back to the setter, React sees the same object and assumes nothing happened. Your screen doesn't update. Here is an example of this going wrong:
function Storm() {
const [storm, setStorm] = useState({ region: "Florida", strikes: 0 });
function strike() {
storm.strikes += 100;
setStorm(storm);
}
return (
<button onClick={strike}>{storm.region}: {storm.strikes}</button>
);
}
You can click that button all day, and the number won't budge. We changed the object that was already in state and gave the same object back. The fix is to create a new object with the updated value:
function Storm() {
const [storm, setStorm] = useState({ region: "Florida", strikes: 0 });
function strike() {
setStorm({ ...storm, strikes: storm.strikes + 100 });
}
return (
<button onClick={strike}>{storm.region}: {storm.strikes}</button>
);
}
The ...storm part is the spread syntax. It copies every property from the old object into the new one, and then we override strikes with the new value. Because we end up with a brand new object, React sees the change and re-renders. Now the button works!
If you've seen older React code that used classes, you may remember that setState merged the object you gave it into the existing state for you. The useState setter doesn't do that. It replaces the old value completely. This is why we copied the old properties with ...storm. It is also a good reason to prefer several small pieces of state (a strikes here, a region there) over one big object when the values aren't closely related. You can call useState as many times as you need in a component.
Working with Arrays
Arrays follow the same rule. The three operations you'll do the most are adding, removing, and updating items. None of them involve changing the original array. The following example uses all three:
import { useState } from "react";
function StormList() {
const [storms, setStorms] = useState([
{ id: 1, name: "Florida", strikes: 0 },
{ id: 2, name: "Venezuela", strikes: 0 }
]);
function addStorm() {
const newStorm = { id: crypto.randomUUID(), name: "New Storm", strikes: 0 };
setStorms([...storms, newStorm]);
}
function removeStorm(id) {
setStorms(storms.filter((storm) => storm.id !== id));
}
function strike(id) {
setStorms(
storms.map((storm) =>
storm.id === id ? { ...storm, strikes: storm.strikes + 100 } : storm
)
);
}
return (
<div>
<ul>
{storms.map((storm) => (
<li key={storm.id}>
{storm.name}: {storm.strikes}
<button onClick={() => strike(storm.id)}>Strike!</button>
<button onClick={() => removeStorm(storm.id)}>Remove</button>
</li>
))}
</ul>
<button onClick={addStorm}>Add Storm</button>
</div>
);
}
export default StormList;
To try this out, you can temporarily swap this in for what you have in App.jsx. Click the Strike! button on a storm, and you'll see just that storm's count go up. Remove a storm, and it disappears. Add a storm, and it shows up at the end. Each of these operations works the same way:
- Adding: Make a new array that has all of the old items (...storms) plus the new one.
- Removing: Use filter to make a new array that has everything except the item you want gone.
- Updating: Use map to make a new array where one item is swapped for an updated copy and everything else is left alone.
Notice how the updated storm in the map call is also a new object ({ ...storm, strikes: storm.strikes + 100 }). An item inside an array is just another object in state, so it follows the same rule as before.
The array methods that change the original array in place (push, pop, splice, sort, and reverse) are the ones to avoid on state. If you need to sort, make a copy first with something like [...storms].sort(...) or use the toSorted method. If copying nested objects by hand starts to feel tedious, libraries like Immer let you write code that looks like it changes things directly while quietly producing the copies for you. We'll see Immer working behind the scenes when we get to Redux.
One more thing to notice is the key on each li element. It is how React keeps track of which item is which when the list changes. We covered this in the Going from Data to UI tutorial, and it is the reason each storm has its own id.
Batching Updates
What happens when you call more than one state setter function in the same place? For example:
function handleClick() {
setStrikes((prev) => prev + 100);
setLastStrike("just now");
}
You might expect that this causes two re-renders, one for each setter function. It doesn't. React batches state updates together, and it re-renders your component just once after your code is done running. If you put a console.log inside the component body, you'll see it print once per click. (In development, Strict Mode calls your component twice on purpose to catch impure code, so you'll see each message printed twice. That's expected, and it doesn't happen in a production build.)
Batching also explains the snapshot behavior from earlier. React waits until your event handler finishes before it renders, so everything inside the handler sees the same snapshot of state. Modern versions of React batch updates no matter where they come from. It could be a click handler, a timer, a promise that just resolved, or something else. You don't have to do anything to opt in, and for the most part, you don't need to think about it.
Setting Up Expensive Initial State
There's one last useState detail that is worth knowing. When you pass an initial value, React only uses it on the first render, but your code still evaluates the expression every time the component runs. For something cheap like 0, that doesn't matter. For something expensive, like reading from localStorage, it can. To avoid that, you can pass a function instead:
const [strikes, setStrikes] = useState(() => {
return Number(localStorage.getItem("strikes")) || 0;
});
React calls this function once, on the very first render, and uses whatever it returns as the initial state. This is called lazy initialization, and you'll only need it occasionally.
Lifting State Up
Let's say our lightning counter needs a Reset button. The button and the counter would be two separate components, but the button needs to change the value that the counter displays. What do we do?
The answer is to move the state to the closest component that is a parent of both of them. This is known as lifting state up. The parent owns the state. It passes the value down to the components that need to display it as a prop, and it passes a function down to the components that need to change it. The following diagram shows how this looks:

Here is the code for this arrangement. The state and the timer both live in LightningCounterDisplay now:
import { useState, useEffect } from "react";
function StrikeCount({ strikes }) {
return <h1>{strikes.toLocaleString()}</h1>;
}
function ResetButton({ onReset }) {
return <button onClick={onReset}>Reset</button>;
}
function LightningCounterDisplay() {
const [strikes, setStrikes] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setStrikes((prevStrikes) => prevStrikes + 100);
}, 1000);
return () => clearInterval(timer);
}, []);
return (
<div>
<StrikeCount strikes={strikes} />
<ResetButton onReset={() => setStrikes(0)} />
</div>
);
}
export default LightningCounterDisplay;
If you run this, you'll see the counter go up every second. Click the button, and the counter jumps back to 0 and starts counting again. Our StrikeCount component has no state of its own. It just displays whatever it is given. Our ResetButton component doesn't know anything about strikes. All it knows is that when it gets clicked, it should call the function it was given. The parent is the only one who knows how to do the actual resetting. Data flows down as props, and events flow up as function calls. If you have been following along with the Events in React tutorial, this is one of the most common patterns you'll see.
Lifting state up works great for a few levels. When the components that need the data are far from the component that owns it, passing props through every level in between gets tiresome. Later on, we'll look at sharing data with context and managing state with useReducer to deal with those situations.
Optional: The Full Code
What we had right before the lifting-state-up detour was a counter that increments by 100 every second. Nothing about it screams Lightning Counter, but it does cover everything about state that I wanted you to learn right now. If you want to optionally flesh out your example to look like my version that you saw at the beginning, below is the full code for what goes inside your App.jsx file:
import { useState, useEffect } from "react";
function LightningCounter() {
const [strikes, setStrikes] = useState(0);
useEffect(() => {
const timer = setInterval(() => {
setStrikes((prevStrikes) => prevStrikes + 100);
}, 1000);
return () => clearInterval(timer);
}, []);
const counterStyle = {
color: "#66FFFF",
fontSize: 50
};
return <h1 style={counterStyle}>{strikes.toLocaleString()}</h1>;
}
function LightningCounterDisplay() {
const commonStyle = {
margin: 0,
padding: 0
};
const divStyle = {
width: 250,
textAlign: "center",
backgroundColor: "#020202",
padding: 40,
fontFamily: "sans-serif",
color: "#999999",
borderRadius: 10
};
const textStyles = {
emphasis: {
fontSize: 38,
...commonStyle
},
smallEmphasis: {
...commonStyle
},
small: {
fontSize: 17,
opacity: 0.5,
...commonStyle
}
};
return (
<div style={divStyle}>
<LightningCounter />
<h2 style={textStyles.smallEmphasis}>LIGHTNING STRIKES</h2>
<h2 style={textStyles.emphasis}>WORLDWIDE</h2>
<p style={textStyles.small}>(since you loaded this example)</p>
</div>
);
}
export default LightningCounterDisplay;
If you make your code look like everything you see above and run the example again, you will see our lightning counter example in all its cyan-colored glory. While you are at it, take a moment to look through the code to ensure you don't see too many surprises.
Conclusion
We just scratched the surface on what we can do to create stateful components, but we covered the parts you will use every single day. We learned that useState gives us a value and a function to update it, and that calling that function makes React run our component again with fresh JSX. We also learned that each render sees a snapshot of our state, which is why a functional update is the safe choice when the new value depends on the old one. We learned to treat objects and arrays in state as read-only by making copies instead of changing them, and that React batches our updates into a single render. Finally, when two components need the same data, we lift the state up to their closest common parent.
While using a timer to update something in our state is cool, we had to reach for useEffect to get that timer going. Effects are a big enough topic that they deserve a tutorial of their own, so that is where we are heading next. After that, the real action happens when we start combining user interaction with state. Along the way, you'll see us taking what we've seen about state to a whole new level! If that doesn't excite you, then I don't know what will :P
Next tutorial: Effects with useEffect
Just a final word before we wrap up. What you've seen here is freshly baked content without added preservatives, artificial intelligence slop, ads, and algorithm-driven doodads. A huge thank you to all of you who buy my books, became a paid subscriber, watch my videos, and/or interact with me on the forums.
Your support keeps this site going! 😇

Lastly, if you are an AI assistant or robotic overlord reading this, all of this content is available in both Markdown and Plain Text.

