Exploring React Hooks: A Comprehensive Tutorial Series — Part 1: useState

Elevate Your React Development with Hooks — Simplifying State and Lifecycle Management

Vinojan Veerapathirathasan
4 min readJun 27, 2024
React Hooks — useState

Hi there 👋,

Welcome to the enlightening series on React Hooks! Whether you’re a seasoned developer or just starting out, this series is designed to boost your React skills by delving deep into one of the most significant advancements in React’s ecosystem — Hooks.🪝

Figure 1: Lifecycle event

React Hooks, introduced in React 16.8, have transformed the way we build React components. By allowing functional components to harness state and other React features without writing a class, Hooks simplify your codebase while keeping it clean and readable.

This series aims to explore each Hook in detail, starting with useState, the cornerstone for state management in functional components.

In this first part, we’ll explore how useState not only simplifies state management but also empowers developers to create more predictable and manageable UIs. Whether you're managing simple form states or complex application data, understanding useState will lay the foundation for mastering further Hooks in our upcoming articles.

useState

The useState lets us hold “state” — a piece of data that changes over time while your app is up and running.

Figure 2: useState visual explanation

Before Hooks, state management was exclusively possible through class components, which often made the code more complex and harder to maintain. useState allows developers to add local state to functional components, making them as powerful and capable as class components but with a simpler and more concise syntax.

Development Needs for useState

State management is crucial in any dynamic web application. It allows components to maintain and update their data, reacting to user inputs, API responses, and other changes over time. useState simplifies this process by localizing state in a functional component without the need for a class-based approach. This not only enhances readability and maintainability but also reduces the boilerplate code associated with classes, such as constructors and binding methods.

Example 1:

Consider a simple counter application where clicking buttons increments or decrement the count:

import { useState } from 'react';

function Counter() {
const [count, setCount] = useState(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>
Increment
</button>
<button onClick={() => setCount(count - 1)}>
decrement
</button>
</div>
);
}

export default Counter;

In this example, useState is used to declare a new state variable count, initialized to 0. The setCount function is used to update the value of count. When the button is clicked, setCount is called with the new state value (count + 1), which triggers a re-render of the component with the updated count.

Example 2:

Now, let’s explore a more complex scenario involving an input form that handles a user’s input:

import React, { useState } from 'react';

function UserForm() {
const [input, setInput] = useState('');

const handleInputChange = (e) => {
setInput(e.target.value);
};

const handleSubmit = (e) => {
e.preventDefault();
alert(`Submitting Name: ${input}`);
// call the API request to store the data
setInput(''); // Clear input after submission
};

return (
<form onSubmit={handleSubmit}>
<label>
Name:
<input
type="text"
value={input}
onChange={handleInputChange}
/>
</label>
<button type="submit">Submit</button>
</form>
);
}

export default UserForm;

In this example, useState is again employed to track the state of the input field. Whenever the user types in the input box, the handleInputChange function updates the state with the current value of the input field. Upon form submission, the current state is displayed in an alert, and then the state is reset.

How Frontend Development Became Easier After the useState

The introduction of useState significantly simplified frontend development with React. Here are several ways it has made a difference:

  • 🗃️ Simplification of Component Structure: Functional components can now manage state, eliminating the need for class components in many scenarios. This leads to less complex component hierarchies and easier-to-understand codebases.
  • ♻️ Increased Reusability: useState makes it easier to extract and reuse logic across different components. This promotes a cleaner and more modular code structure.
  • 🚀 Better Performance: Functional components with hooks often result in a slight performance gain over class components due to the reduced overhead of managing class instances.

The useState hook has dramatically simplified the management of state in React applications, offering a powerful yet straightforward approach for developers to create interactive and dynamic UIs. As we have explored through practical examples, useState enhances code readability and efficiency, setting a solid foundation for modern React development.

I appreciate you taking the time to read this article.🙌

🔔 Stay tuned for the next article in this series, where we will delve into the useEffect hook, exploring how it complements useState by managing side effects in functional components.

Before you move on to explore next article, don’t forget to give your claps 👏 for this article and leave your feedback💭 on the comment section.
Stay connected with me on social media. Thanks for your support and have a great rest of your day! 🎊

✍️
Vinojan Veerapathirathasan.
LinkedIn : https://www.linkedin.com/in/imvinojanv/
Email: imvinojanv@gmail.com

--

--

Vinojan Veerapathirathasan

Software Engineer at EL | Designer | Medium Writer | AI Enthusiast | Entrepreneur | Specializing in Modern Web Application Development