While learning React back in 2022, state was one of the most confusing topics for me. I remember staying up late at night on few occasions trying to hack my way through finding out why it was vital to building React applications, and what made it so special. It's 2024 now, I still learn new things about state and I've come to realize that state is the lifeblood of any React application. This article is a simple guide to understanding state in React and I hope you find it helpful and informative. Cheers to learning! š
Table of contents
- Introduction
- What does it mean for a component to have state?
- What should a component remember?
- Giving a component state
- Summary in snippets
Introduction
A react application can be described as a sea of components working together for usually two purposes. To display UI to users and to provide a way for users to interact with UI. The bulk of React applications in the world revolve around these two purposes. A React application can be described as a sea of components working together for usually two purposes: to display UI to users and to provide a way for users to interact with that UI. The bulk of React applications in the world revolve around these two purposes.
What does it mean for a component to have state?
State is a vital part of every React application. State is how you make react components come alive. When a component has state, it can help you remember when data changes and reflects the new data in the UI. So how then do you know whether to give a component state? Whatās the importance of giving a component state? Must all your React components have state? To answer these questions, we need to explore what it means to give a component state.
In simple words, giving a component state is you telling the component
Heyy, Iām giving you state because I want you to help me remember something. I need you to help me track a particular piece of data, and when that data changes, refresh yourself and display the new data to the user.
So in summary, state is simply a componentās memory. It is a way for components to rememberĀ āthingsā.
What Should a Component Remember?
When I mean that state is a way for components to remember things, the things in context is simply data. React applications are data-driven. This means that they are strongly influenced by data. Letās break this down. I read an article by expert Engineer Kent C. Dodds. In this article he quoted something saying, āWeb applications are just a skin on top of a database.ā Check out the article here. What this means is that a React application is the interface between data and users. And the amazing thing about data is that it changes, itās dynamic, it doesnāt always remain constant.
An Example
When you go to the bank, you usually want to go interact with some ādataā. See the bank as a React application. The data in context is your money. Remember that data is dynamic, it changes, it doesnāt always remain constant. So at the bank you can add to your money, subtract from it or do anything you want with it. But somehow, you canāt just walk into any bank and go directly to where your money is kept. You need some interface, a skin over your data, you need to interact with the bank official.
Web applications are just a skin on top of a database.
In this context, the bank official is our user interface. When you get a deposit, your data changes and then the bank official needs to fetch your new balance and then display it to you. As you interact with the bank thereby causing the data to change, that's how a user interacts with a React application, also causing the data to change.
Here are examples of how a user can interact with a React application thereby causing some data to change. A user could:
- Click a button to add to their money
- Click a button to subtract from their money
- Click a button to transfer money to another account
- Click a button to withdraw money from their account
- A user can click a button to deposit money to their account
- Submit a form to change app password
- Add a song to a music playlist
- Add a product to a shopping cart
- Delete a post on a social media app
All these interactions cause some data to change. A React application needs to be smart enough to know when the data changes and then reflect that change in the UI. The way to give a React application this ability is by giving it state.
Now, let's explore this React component. It's a straightforward bank application that enables you to deposit and withdraw funds. Feel free to experiment with saving and withdrawing some money. šµ š°
Welcome back
Balance: $1,000,000
Save
Withdraw
You may observe that your balance remains unchanged when you click the buttons. Why is this so? Why does the balance seem stuck? To answer these question, let's take a look at the code and what happens in the console. Try clicking the buttons once again and observe the console. š
Voila! Our balance actually gets updated but it doesn't get displayed in our user interface. This is because the JSX part of the React code doesnt know that the balance has changed. As shown in the console, the balance variable gets updated each time we click the buttons but the UI isn't aware about this change, so it just keeps displaying the initial balance. š¤·
Like the bank example I gave earlier, imagine that you make some deposits and withdrawals to your account. You go to the bank to check your balance and discover that your balance is not updated. This is because the bank official isn't aware of the changes you made to your account. So he has to find a way to remember the data changes you made to your account. Likewise in React applications, we need to find a way to give components the ability to remember data changes and then display the new data to the user. This is where state comes in. šÆ
Giving a component state
We need to give our balance state to the JSX part of the React code. We can do this by using the useState hook. According to the React documentation,
useState is a React Hook that lets you add a state variable to your component.
The useState hook takes an initial value which could be a number, string, boolean, array, object, etc. and then returns an array with two values. The first value is the state variable and the second value is a function that allows us to update the state variable.
const [balance, setBalance] = useState(1000000);
In this example:
- balance is the state variable
- setBalance is a function that React provides for us to update the state variable
Now when the data changes via making deposits and withdrawals, React is aware of it and would automatically refresh the UI to display the new data. This is the magic of state in React. Let's see this in action.
So our balance gets updated and displayed correctly because our React application is aware of the changes. In the example without state, we manually had to write some logic to update the balance variable by doing this:
const updateBalance = (amount, isDeposit) => {
if (isDeposit) {
// Manually updating the balance variable
// 'balance' is updated but React is unaware, so UI stays the same
balance += amount;
} else {
if (balance >= amount) {
// Same here, manually updating the balance variable
// 'balance' is updated but React is unaware, so UI stays the same
balance -= amount;
} else {
alert("Insufficient funds for this withdrawal.");
}
}
};
Now, our balance variable gets updated directly by the setBalance function which triggers React to update the variable and refresh the UI.
const updateBalance = (amount, isDeposit) => {
if (isDeposit) {
// Using the 'setBalance' function.
// 'balance' is updated and React is aware, so UI is refreshed
setBalance(balance + amount);
} else {
if (balance >= amount) {
// Using the 'setBalance' function.
// 'balance' is updated and React is aware, so UI is refreshed
setBalance(balance - amount);
} else {
alert("Insufficient funds for this withdrawal.");
}
}
};
Summary in snippets š
- State is a component's memory. It is a way for components to remember things.
- State is how you make react components come alive.
- State allows components to remember data changes and then display the new data to the user.
- useState is a React Hook that lets you add a state variable to your component.
- useState takes an initial value and returns an array with two values: the state variable and a function to update the state variable.
- The state setter function can be named anything, it doesn't have to be setState, it can be named anything like setBalance, setName, setAge, etc.
- When the state variable changes, React is aware of it and automatically refreshes the UI to display the new data.
- All React components can have state.
Now let's test your knowledge with a quiz.
Hope you enjoyed this blog post. See you in the next one! š