Forem

Cover image for Simplifying React Hooks: useState πŸ’―
Ali Samir
Ali Samir

Posted on

Simplifying React Hooks: useState πŸ’―

React Hooks revolutionized how we write components in React by allowing us to use state and other features in functional components.

One of the most fundamental and widely used hooks is useState. In this article, we’ll break down useState in a simple and approachable way, complete with examples using TypeScript.


What is useState? πŸ€”

useState is a React Hook that allows you to add state to functional components. Before hooks, state management was only possible in class components.

With useState, you can now declare and manage the state directly in functional components.


How Does It Work? βš™οΈ

useState returns an array with two elements:

1- The current state value.

2- A function to update the state.

Here’s the basic syntax:

const [state, setState] = useState(initialState);
Enter fullscreen mode Exit fullscreen mode

state: The current value of the state.

setState: A function used to update the state.

initialState: The initial value of the state.


A Simple Example βœ…

Let’s start with a basic example: a counter component.

import React, { useState } from 'react';

const Counter: React.FC = () => {
  const [count, setCount] = useState<number>(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
};

export default Counter;
Enter fullscreen mode Exit fullscreen mode

Explanation:

1- We import useState from React.

2- We declare a state variable count with an initial value of 0. The type number is explicitly specified using TypeScript.

3- We render the current value of count and a button that updates the state when clicked using setCount.


Using useState with Complex Types πŸ’ͺ🏻

useState isn’t limited to primitive types like numbers or strings. It can also handle objects, arrays, and other complex data structures.

Let’s look at an example where we manage a user object.

import React, { useState } from 'react';

interface User {
  name: string;
  age: number;
  email: string;
}

const UserProfile: React.FC = () => {
  const [user, setUser] = useState<User>({
    name: 'John Doe',
    age: 25,
    email: 'john.doe@example.com',
  });

  const updateName = () => {
    setUser({ ...user, name: 'Jane Doe' });
  };

  return (
    <div>
      <p>Name: {user.name}</p>
      <p>Age: {user.age}</p>
      <p>Email: {user.email}</p>
      <button onClick={updateName}>Change Name</button>
    </div>
  );
};

export default UserProfile;
Enter fullscreen mode Exit fullscreen mode

Explanation:

1- We define a User interface to type the state.

2- We initialize the state with a user object.

3- When updating the state, we use the spread operator (...user) to ensure we don’t lose the other properties of the object.


Handling Multiple State Variables ⚑

You can use useState multiple times in a single component to manage different pieces of state independently.

import React, { useState } from 'react';

const Form: React.FC = () => {
  const [name, setName] = useState<string>('');
  const [age, setAge] = useState<number>(0);
  const [isEmployed, setIsEmployed] = useState<boolean>(false);

  return (
    <div>
      <input
        type="text"
        placeholder="Name"
        value={name}
        onChange={(e) => setName(e.target.value)}
      />
      <input
        type="number"
        placeholder="Age"
        value={age}
        onChange={(e) => setAge(Number(e.target.value))}
      />
      <label>
        <input
          type="checkbox"
          checked={isEmployed}
          onChange={(e) => setIsEmployed(e.target.checked)}
        />
        Employed
      </label>
    </div>
  );
};

export default Form;
Enter fullscreen mode Exit fullscreen mode

Explanation:

1- We use three separate useState hooks to manage name, age, and isEmployed.

2- Each state variable is updated independently based on user input.


Key Takeaways ✍🏻

  • useState is simple yet powerful: It allows you to add state to functional components with minimal code.

  • TypeScript enhances useState: By explicitly typing your state, you can catch errors early and improve code readability.

  • You can use multiple useState hooks: This helps keep your state management organized and modular.


Conclusion βœ…

useState is the foundation of state management in functional React components.

By understanding how it works and practicing with examples, you’ll be able to build dynamic and interactive applications with ease.

In the next article in this series, we’ll dive into another essential hook: useEffect. Stay tuned! πŸš€


🌐 Connect With Me On:

πŸ“ LinkedIn
πŸ“ X (Twitter)
πŸ“ Telegram
πŸ“ Instagram

Happy Coding!

Top comments (0)