React useState Hook Tutorial
Build a Counter App with React and useState.

I'm developer and technical writer passionate about creating exceptional software solutions and crafting engaging technical content. With a strong background in software development and a flair for effective communication, I bring a unique blend of technical expertise and writing skills to my work.
Introduction
In the ever-evolving landscape of web development, React has become popular for building interactive and dynamic user interfaces. React is a component-based Javascript library and one of the most important concepts in React is to manage the state of components in an application, and useState hook is a fundamental concept for doing that.
State management in React is like the memory that enables dynamic and responsive user interfaces. It allows components to remember and react to user interactions, creating a seamless and interactive user experience.
In this article, we'll explore the practical usage of the useState hook in React through a basic counter app. Project-based learning has proven to be one of the most efficient ways to grasp new concepts in programming. So, without further ado, let's get right into it!
Pre-requisite
Basic javascript knowledge.
Basic react knowledge(Functional components, JSX ).
What are React Hooks?
React hooks are functions that allow functional components to utilize React features, it was introduced in React 16.8 to enhance state management. Types of React Hooks include useState, useEffect, useRef, useReducer, and so on.
In this article, we are going to focus on the useState hook.
What is a state?
State is like the memory of a component's status or value, that allows it to respond to user interactions and update the user interface accordingly. It is often used to store and manage dynamic data that can change over time.
When do you need state?
You need state in your application or component when you want to:
Manage and Track Data Changes: State is used to keep track of data that can change over time. This could be user input, data fetched from an API, or any other dynamic data that needs to be displayed or used within your application.
Enable Interactivity: State is crucial for creating interactive user interfaces. It allows your components to respond to user actions, such as button clicks, form submissions, or mouse events.
Reflect Application State Changes: When something in your application changes, you often need to update the user interface to reflect those changes. State helps you manage these updates efficiently.
Here are some specific scenarios where you commonly need state:
Counter Components: When building counters or progress trackers, state is used to store and update the count or progress value(which is why we would be building a counter app in this article to master the
useStateconcept).Forms: State is crucial for handling form inputs, storing user-entered data, and validating it.
User Authentication: State can be used to track whether a user is logged in or logged out and control access to certain parts of the application.
What are State Variables?
State variables are commonly used to control what is displayed on the user interface and to manage the behaviour of components. For example, a form component can use state to store the input value.
Types of state variables
Local variable: Local state variables are specific to a single component. They are created and managed using the
useStatehook (in functional components).Global variable: Global state variables are shared and accessible across multiple components. They are typically managed using state management libraries like Redux .
Derived variable: Derived state variables are computed based on existing state or props. These variables are not directly stored in state but are calculated as needed.
Note: In this article, we will focus on local variables which are managed with the
useStatehook.
What is the useState hook?
useState is a React hook that manages the state in functional components by adding a state variable to the component. It works by providing two elements:
State variable: You declare a state variable using
useState. This variable holds the current state value and serves as a reference to the state data.Setter Function: React automatically generates a setter function associated with the state variable. This function will be called to update the state when needed.
How does useState work?
Using the useState hook is a straightforward process that involves three simple steps. Let's dive right in!
Declare the State:
Initialize the state variable and the setter function.Example:
const [count, setCount] = useState(0);Here,
countrepresents the state variable,setCountis the setter function, anduseState(0)sets the initial value ofcountto 0. You can set it to any value you prefer.const [count, setCount] = useState(0);
Consume the State:
Use the state variable within the JSX of your functional component.
function Counter() { const [count, setCount] = useState(0); return <button>{count}</button>; }The initial value of
countwill be displayed within the button element.
Update the State:
Modify the state based on user interactions, such as button clicks, mouse hover events, or key presses.
Utilize the setter function by attaching it to the corresponding element or event handler.
function Counter() { const [count, setCount] = useState(0); function addCount() { setCount(count + 1); } return <button onClick={addCount}>{count}</button>; }When the user clicks the button, the
addCountfunction is invoked, which updates the state variable.
By following these three simple steps, you can effectively use the useState hook to manage and update state in your React functional components.
Note: Avoid calling the function directly because React executes it immediately upon program execution. Instead, write it as a reference, allowing React to invoke it upon a button click.
What happens when the state is updated?
React automatically re-renders the component to reflect the new state value in the user interface. With these 3 steps above you can always utilize the useState hook.
A simple counter app
Let's explore a basic counter app to further understand how useState works. To get started, you can use create-react-app for this project. Alternatively, follow this quick start link for a simplified setup.
Once you've clicked on the quick start link, make sure your code resembles this;

Now, let's create the Counter functional component, adhering to React's best practices for breaking the UI into components.
Note: The CSS styling of this simple project has been added, CSS is not the focus of this article. you can check the final project link and copy the CSS styling from there or you can style yours as you wish, so go on and play with it!

Our Counter app is live and ready! Now, let's implement the useState hook.
Remember the 3steps to useState hook.
Declare the state: make sure to import
useStatefrom react as seen(line 2) for it to work. Since it is a local variable it is declared inside the function component.
Consume the State : Observe how the
countvariable is used within the<p>element for rendering. Initially set to 0 (line 14), this is why we see 0 on the screen.
Update the state: To make the counter work correctly, we need to implement both the addition (+) and subtraction (-) functionality. This requires updating the state since the
countvalue changes with each user click on the button. Utilize the setter function as shown below (line 15).
Remember to attach this function to the onClick event handler of the button element. This way, when users click the button, React invokes the function, updating the state (line 24). As a result, the counter now functions as expected!
Repeat the same process for the subtraction (-) button, decrementing by 1. You can find the final code Here. Your counter app should be working flawlessly. Congratulations!
The App is live on Code sandbox as seen below
Now that you've gained a solid understanding of how the useState hook functions and how to effectively implement it, you're ready to harness its power in your projects. Dive in, experiment, and hone your skills. Remember, mastery comes through practice and persistence. Best of luck on your coding journey, and stay tuned for more insightful articles in the future!


