If you want to incorporate state in a functional component, you can do so like this: (example sourced from this reference: https://reactjs.org/docs/hooks-intro.html)
import React, { useState } from 'react';
function Example() {
// Define a new state variable called "count"
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
To simplify this concept further,
const [count, setCount] = useState(0);
essentially signifies the same idea as
this.state = {
count: 0; // The count state variable starts at 0
}
setCount(newStateCount) {
count = newStateCount; // You update the state using setCount(1), for instance.
// So now count goes from 0 to 1 in this case.
}
React handles the implementation of both tasks within that single line, requiring only a call to setCount to modify the count state rather than this.state.count = newValue
.
In response to a question under the initial answer: You can set state for multiple properties like this: how to write a multi lines state with Hooks useState in ReactJs
const [state, setState] = useState({
step: 1,
firstName: '',
lastName: '',
jobTitle: '',
jobCompany: '',
jobLocation: '',
});
// Updating state as follows:
setState(prev=>{...prev,firstName:'Joey'});