State reactivity in React
Now let's look at how reactivity works. It makes sure that when the state changes, the changes are instantly reflected on the screen.
Let's look at an example. Let's say we have a state with a product name:
const [name, setName] = useState('prod');
Let's display the product name in the layout:
return <div>
<span>{name}</span>
</div>;
Now let's make a button, by clicking on which our state will change:
return <div>
<span>{name}</span>
<button onClick={clickHandler}>btn</button>
</div>;
In the click handler, we use the setName function to set a new name for the product:
function clickHandler() {
setName('xxxx');
}
Let's put all our code together. It turns out that after pressing the button, the text will instantly change to a new value:
function App() {
const [name, setName] = useState('prod');
function clickHandler() {
setName('xxxx');
}
return <div>
<span>{name}</span>
<button onClick={clickHandler}>btn</button>
</div>;
}
Using separate handler functions is not necessary. An anonymous arrow function can be used:
function App() {
const [name, setName] = useState('prod');
return <div>
<span>{name}</span>
<button onClick={() => setName('xxxx')}>btn</button>
</div>;
}
States with the user's first and last name are given. Display them in the layout. Make buttons to change these states.