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:

jsxconst [name, setName] = useState('prod');

Let's display the product name in the layout:

jsxreturn <div>
  <span>{name}</span>
</div>;

Now let's make a button, by clicking on which our state will change:

jsxreturn <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:

jsxfunction 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:

jsxfunction 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:

jsxfunction App() {
  const [name, setName] = useState('prod');
  
  return <div>
    <span>{name}</span>
    <button onClick={() => setName('xxxx')}>btn</button>
  </div>;
}
Задание 1

States with the user's first and last name are given. Display them in the layout. Make buttons to change these states.