Using States in React
Let's use the useState function to create a state containing the product name:
const state = useState('prod');
As a result, the constant state will be an array, the first element of which will store the name of the product, and the second - a function for changing the name:
const state = useState('prod');
const name = state[0];
const setName = state[1];
For brevity, it is common not to use an intermediate constant for an array, but to use destructuring:
const [name, setName] = useState('prod');
Let's now output our state with the product name in some layout:
return <p>
<span>{name}</span>
</p>;
Let's put it all together and get the following code:
import React, { useState } from 'react';
function App() {
const [name, setName] = useState('prod');
return <div>
<span>{name}</span>
</div>;
}
export default App;
If you run this code, the initial value of the state will be displayed in the div, in our case 'prod'. When changing the state via the setName function and the layout, a new state value will automatically appear.
Let's say you want to display user data on the screen: his name, last name, age. Make appropriate states with initial values for this.