React State & Re-renders
Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" should change which image is displayed. Components need to "remember" things. In React, this kind of component-specific memory is called state.
Adding a state variable
To add a state variable, import useState from React at the top of the file:import { useState } from 'react';
Then, declare a state variable inside your component. useState gives you two things: a state variable to retain the data between renders, and a state setter function to update the variable and trigger React to render the component again.
Anatomy of useState
The convention is to name this pair like const [something, setSomething]. You could name it whatever you like, but conventions make things understandable across projects.
State is isolated and private
State is local to a component instance on the screen. In other words, if you render the same component twice, each copy will have completely isolated state! Changing one of them will not affect the other.
View Full Deep Dive+
Unlike regular variables, state variables persist across renders. React remembers their values as long as the component exists in the DOM tree. Never mutate state variables directly. If you have an object or array in state, you must pass a completely new object or array to the setter function (using the spread operator ...) to ensure React detects the change and triggers a re-render.
