You can use state in a functional component as follows: (example taken from this link: https://reactjs.org/docs/hooks-intro.html)
import React, { useState } from 'react';
function Example() {
// Declare a new state variable, which we'll call "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
To break this down,
const [count, setCount] = useState(0);
basically means the same thing as
this.state = {
count: 0; // 0 is what the count state variable initializes to
}
setCount(newStateCount) {
count = newStateCount; // you change the state using setCount(1), for example.
// now count goes from 0 to 1 in this case.
}
React basically does the implementation of both for you in that single line, and all you have to do is call setCount in order to change the count state instead of this.state.count = newValue
.
In response to the comment under this original answer: You can set state for multiple properties like so: how to write a multi lines state with Hooks useState in ReactJs
const [state, setState] = useState({
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
});
// Setting state like:
setState(prev=>{...prev,firstName:'Joey'});