📜  typed usestate - TypeScript (1)

📅  最后修改于: 2023-12-03 15:05:38.774000             🧑  作者: Mango

Typed useState - TypeScript

Introduction

In this article, we will discuss about using the useState hook in TypeScript with proper typing.

useState is a hook provided by React which is used to manage state in functional components. It takes an initial state as input and returns an array containing the current state and a function to update the state.

Typing the state and updater function with TypeScript enables better code completion and prevents errors due to incorrect usage of the state.

Usage

The useState hook can be used in TypeScript by providing a generic type to the useState function call. The generic type represents the type of the state.

Here is an example of using useState with TypeScript:

import { useState } from 'react';

type CounterState = {
  count: number;
}

const Counter = () => {
  const [state, setState] = useState<CounterState>({ count: 0 });

  const handleIncrement = (): void => {
    setState({ ...state, count: state.count + 1 });
  };

  const handleDecrement = (): void => {
    setState({ ...state, count: state.count - 1 });
  };

  return (
    <div>
      <p>Count: {state.count}</p>
      <button onClick={handleIncrement}>+</button>
      <button onClick={handleDecrement}>-</button>
    </div>
  );
};

export default Counter;

In the above example, we have provided the CounterState type as the generic argument to useState. This enables us to access the count property of the state without any errors.

Conclusion

Using useState with proper typization in TypeScript can help prevent errors, improve code completion and make the code more readable. We should always strive to use typing with our React code for better maintainability.

Hope you found this article helpful!