DEV Community

Cover image for Mastering 'useState' in React with TypeScript: 5 Different Use-Cases for 'useState'
Kirubel Kinfe
Kirubel Kinfe

Posted on • Updated on

Mastering 'useState' in React with TypeScript: 5 Different Use-Cases for 'useState'

In React, the 'useState' hook is a fundamental piece of state management that allows developers to manage and update component state. When used in conjunction with TypeScript, it provides a strong type system that ensures type safety and helps prevent runtime errors. In this article, we'll explore the various use cases of 'useState' in React, with a focus on best practices for TypeScript projects.

Understanding useState
The useState hook is part of the React Hooks API, introduced in React 16.8. It allows functional components to manage local state by providing access to a state variable and a function to update it. Here's a basic example:

import React, { useState } from 'react';

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

  const increment = () => {
    setCount(count + 1);
  };

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, useState is used to declare a state variable called count initialized to 0, and a function setCount to update it.

Use Cases for useState in React and TypeScript
1. Managing Local Component State
The most common use case for useState is managing local component state. You can use it to store and update data that is specific to a single component, such as form input values, visibility toggles, or counters, as shown in the example above.

2. Form Handling
useState is particularly useful for handling form inputs. You can use it to capture and update user input, ensuring that your form stays in sync with the component's state:

import React, { useState } from 'react';

function Form() {
  const [formData, setFormData] = useState<{ name: string; email: string }>({
    name: '',
    email: '',
  });

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  return (
    <form>
      <input
        type="text"
        name="name"
        value={formData.name}
        onChange={handleChange}
        placeholder="Name"
      />
      <input
        type="email"
        name="email"
        value={formData.email}
        onChange={handleChange}
        placeholder="Email"
      />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, formData is a state variable that holds the form data, and setFormData updates it as the user types.

3. Conditional Rendering
useState can also be used for conditional rendering. You can maintain a boolean state variable to toggle the visibility of certain elements or components:

import React, { useState } from 'react';

function ToggleableComponent() {
  const [isVisible, setIsVisible] = useState<boolean>(false);

  const toggleVisibility = () => {
    setIsVisible(!isVisible);
  };

  return (
    <div>
      <button onClick={toggleVisibility}>Toggle</button>
      {isVisible && <p>Visible content</p>}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, the isVisible state controls the visibility of the

element.

4. Resetting State
You can use useState to provide a mechanism for resetting state to its initial values. For example, in a settings page, you might allow users to reset their preferences to default values:

import React, { useState } from 'react';

function Settings() {
  const [preferences, setPreferences] = useState<{ theme: string; fontSize: number }>({
    theme: 'light',
    fontSize: 16,
  });

  const resetPreferences = () => {
    setPreferences({ theme: 'light', fontSize: 16 });
  };

  return (
    <div>
      <button onClick={resetPreferences}>Reset Preferences</button>
      <p>Theme: {preferences.theme}</p>
      <p>Font Size: {preferences.fontSize}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, clicking the "Reset Preferences" button resets the preferences state to its default values.

5. Complex State
useState can handle more complex state structures, including objects and arrays. This is especially useful when you need to manage multiple pieces of data in a single state variable:

import React, { useState } from 'react';

function ComplexState() {
  const [data, setData] = useState<{ name: string; age: number }[]>([
    { name: 'Alice', age: 25 },
    { name: 'Bob', age: 30 },
  ]);

  return (
    <ul>
      {data.map((item, index) => (
        <li key={index}>
          Name: {item.name}, Age: {item.age}
        </li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

In this example, data is an array of objects, and setData updates the state.

Conclusion
useState is a powerful hook in React that allows functional components to manage local state effortlessly. When used in conjunction with TypeScript, it provides type safety and helps prevent common runtime errors. Understanding the different use cases of useState is crucial for building robust and maintainable React applications. Whether you're managing simple counters or complex forms, useState is a versatile tool that plays a key role in state management within your React components.

Top comments (0)