useState is a hook what you use in a React function to create a state variable. This is not used if you use React class components. useState has tricks you must know about.
Source code viewer
import React, { useState } from 'react'; function Example() { // useState hook. Declare a new state variable, in the top level only. Called every time on render. const [count, setCount] = useState(0); // The default value is run only once. Not on every render. const [count, setCount] = useState(() => 0); // Object as a value of state. const [objState, setObjState] = useState({ count: 0, name: 'Object State' }); function increaseCount() { // Can't run more than once. setCount(count + 1); // Can run multiple times, this is a better way to set state. setCount((prevCount) => prevCount + 1); // Setting object values doesn't merge the values automatically, so this code will delete name property of our object. setCount((prevObjState) => { count: prevObjState.count + 1 }); // Correct way to update object. setCount((prevObjState) => { ...prevObjState, count: prevObjState.count + 1 }); } return ( <div> <p>You clicked {count} times</p> <button onClick={increaseCount}> Click me </button> </div> ); }Programming Language: ECMAScript