State
In React, state refers to mutable data that often changes as a result of user interaction. When it changes, the UI must be updated.
import { useState } from "react";
function App (props) {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
export default App;
The useState
Hook takes the initial state as an argument (we passed 0
). It returns an array with two elements: the current state (count
) and a function to change the state (setCount
).
The general syntax for employing useState
is:
const [state, setState] = useState(initialState);
The useState
Hook returns an array. The bracket syntax [state, setState]
to the left of the equal sign is array destructuring.
The state
variable always contains the (latest) state. To update the state, you must use the setState
function. Only then React will know the state has been updated, and it will re-render the UI.
With useState
, it's common to name the returned values like foo
and setFoo
, but you can call them whatever you like. If you are from the OOP world, it might help to think about these two as a "getter" and a "setter" for an attribute!
The useState
is a JavaScript function built into the React library. You must import it before using it.
import { useState } from "react";
Originally, React class components were meant to be state-full components and function were to be state-less. However, this limitation was uplifted by the introduction of React Hooks (since React 16.8). Since then, function components can hold state too. When you use Hooks in a function component, React creates an object to live alongside it. In this object, React stores the state (and other metadata) about the component. There is no magic! It's a hack to allow you to use "state" with functions, a programming construct that is naturally stateless!