useState()
HookTo this point, state has been owned and managed solely in Class based React components, using this.state
with this.setState()
and instance methods to manage it all.
Newer versions of React now allow for “function components” to also manage their own state, using a newly exposed API, called “Hooks”
React hooks allow to to easily create and manage state in a functional component.
Hooks are JavaScript functions, but they impose additional rules:
use
prefix (i.e. useFishingPole
)useState()
Returns a stateVariable and setterFunction for you to use to manage state in a functional component
In this example …
clicks
is the state variable, which will store the number of clickssetClicks
is a function that is called to change the value of clicksHow does this work?
set
+ statevariable
(camel cased) to name this functionuseState()
takes a single param, which is the initial value to assign to the state variablesetClicks(7)
and the attribute value you call the function with is used as the new value for the state variable. import React from 'react';
import { useState } from 'react';
function Counter() {
const [clicks, setClicks] = useState(0);
return (
<div>
<h2>Button has been clicked {clicks} time(s)</h2>
<button type="button" onClick={() => setClicks(clicks + 1)}>
Update Count
</button>
</div>
);
}
export default Counter;