React Counter Component with useState

easyTypeScript

Lesson

React useState Hook - Managing Component State

State is one of the most important concepts in React. It represents data that can change over time and causes your component to re-render when updated. Before React hooks, you could only use state in class components, but the useState hook changed everything by bringing state to functional components.

The useState hook allows you to add state variables to functional components. When you call useState, you pass in the initial value and get back an array with two elements: the current state value and a function to update it.

Think of state like a variable that React watches. When you update state, React knows something changed and automatically re-renders your component to reflect the new data. This is what makes React interfaces interactive and dynamic.

The state setter function (the second element returned by useState) is special - it doesn't just change the variable, it tells React "hey, something important changed, please update the screen." This is why you should never modify state directly, but always use the setter function.

State updates in React are also asynchronous, meaning they don't happen immediately. React batches state updates for performance reasons. This is usually not something you need to worry about as a beginner, but it's good to understand that React is optimizing things behind the scenes.

One key principle is that each piece of state should represent a single value or concept. Don't try to cram multiple related values into one state variable - instead, use multiple useState calls for different pieces of data.

Example
1import React, { useState } from 'react'; 2 3const ToggleButton: React.FC = () => { 4 const [isOn, setIsOn] = useState(false); 5 6 const handleClick = () => { 7 setIsOn(!isOn); 8 }; 9 10 return ( 11 <button onClick={handleClick}> 12 {isOn ? 'ON' : 'OFF'} 13 </button> 14 ); 15};
L4useState(false) creates state starting with false value
L7setIsOn updates the state and triggers a re-render
L11The component displays different text based on current state

Key Takeaways

  • •useState adds state to functional components - call it with initial value and get back current value + setter function
  • •Always use the setter function to update state, never modify state directly
  • •State changes trigger re-renders, making your component reactive to user interactions
Loading...