DEV Community

Cover image for Simplifying React Hooks: useState ๐Ÿ’ฏ
Ali Samir
Ali Samir

Posted on

2 1

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!

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay