📘
NavDoc by Bash School
GithubContact
📘
NavDoc by Bash School
  • 🎓Introduction
  • 🐢Getting Started
  • ⚡Changelog
  • 👨‍🚀Maintainers
  • 🛣️Roadmap
  • Fundamentals
    • The Internet
      • Introduction
      • What is a URL
      • What is a port
      • The DNS protocol
      • The TCP protocol
      • The UDP protocol
      • The Web
      • The HTTP protocol
      • Hyperlinks
      • What is a Web browser
      • What is a Web server
    • HTML
      • Your first HTML page
      • Text tags
      • Attributes
      • Links
      • Images
      • Lists
      • Head Tags
      • Container tags
    • CSS
      • Introduction
      • Colors
      • selectors
      • Cascade
      • Specificity
      • Units
      • Advanced selectors
      • Typography
      • The box model
      • The display property
      • Responsive design
  • JavaScript
    • Basics
      • Introduction
      • Literals , Identifiers, Variables
      • Comments
      • The difference between let, const and var
      • Types
      • Operators and expressions
      • Arithmetic operators
      • The assignment operator
      • Operators precedence
      • Strings
      • Numbers
      • Semicolons, white space and sensitivity
      • Arrays
      • Conditionals
      • Loops
      • Functions
      • Objects
      • Arrays + functions
      • OOPS
      • Asynchronous
      • Scope, hoisting, event loop
      • ES Modules
      • Errors and exceptions
      • Built-in objects
        • The global object
        • Object properties
        • Number
        • String
        • Math
        • JSON
        • Date
        • Intl
        • Set and Map
      • More operators
    • Nodejs
      • Getting Started
      • Installation
      • Hello World in Node
      • Modules
      • Packages
      • File Handling
      • HTTP Request
      • Processing Files
      • HTTP
    • Express.js
      • Getting Started
      • Middleware
      • Serve Static Assets
      • How to Send Files to the Client
      • Sessions
      • Validate Input
      • Sanitizing Data
      • Forms
      • File Uploads
    • React
      • Setting up a React project with Vite
      • React Components
      • Introduction to JSX
      • Using JSX to compose UI
      • The difference between JSX and HTML
      • Embedding JavaScript in JSX
      • Handling user events
      • Managing state
      • Component props
      • Data flow
      • Lifecycle events
      • Managing forms in React
      • Install the React Developer Tools
      • Installing Tailwind CSS in a React app
      • Build a counter in React
    • TypeScript
      • Key Benefits
      • Types of Languages
      • The Need for TypeScript
      • What is TypeScript?
      • The tsc Compiler
      • Basic Types in TypeScript
      • tsconfig
      • Interfaces
      • Types
      • Arrays in TypeScript
      • Enums
      • Exporting and importing
    • MongoDB
      • SQL vs. NoSQL Databases
      • Installing MongoDB
      • MongoDB Databases and Collections
      • Working with Documents
      • MongoDB Operators
      • Sorting, Indexing & Searching
      • Built-in Methods
Powered by GitBook
On this page

Was this helpful?

Edit on GitHub
  1. JavaScript
  2. React

Managing state

PreviousHandling user eventsNextComponent props

Last updated 1 year ago

Was this helpful?

Every React component can have its own state.

What do we mean by state? The state is the set of data that is managed by the component.

Think about a form, for example. Each individual input element of the form is responsible for managing its state: what is written inside it.

A button is responsible for knowing if it’s being clicked, or not. If it’s on focus.

A link is responsible for knowing if the mouse is hovering over it.

In React, or in any other components-based framework/library, all our applications are based and make heavy use of components state.

We manage the state using the useState utility provided by React. It’s technically a hook (you don’t need to know the details of hooks right now, but that’s what it is).

You import useState from React in this way:

import { useState } from 'react'

Calling useState(), you will get back: a new state variable, and a function that we can call to alter its value.

useState() accepts the initial value of the state item and returns an array containing the state variable, and the function you call to alter the state.

Here’s an example of how to use useState():

const [count, setCount] = useState(0)

useState() returns an array. The above construct uses a special syntax called which we’ll use all the time to extract from the array the first value in the count variable, and the second value in the setCount variable.

This is important: we can’t just alter the value of a state variable directly, doing count++ or count = count + 1. ****

We must call its modifier function setCount().

Otherwise, the React component will not update its UI to reflect the changes in the data. Calling the modifier is the way we can tell React that the component state has changed.

The syntax is a bit weird, right? Since useState() returns an array we use array destructuring to access each individual item, like this: const [count, setCount] = useState(0)

Here’s a practical example:

import { useState } from 'react'

const Counter = () => {
  const [count, setCount] = useState(0)

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

You can add as many useState() calls as you want, to create as many state variables as you want, which can hold any value, not just numbers (also objects and arrays are valid):

const [count, setCount] = useState(0)
const [name, setName] = useState('John')
array destructuring