4) Learning React – Video 49 – A Closer Look at the useState Hook

This is a video where Max explains the useState hook in a bit more detail.

A separate state is created for each expense item.

A new state is created for each instance of a component.

Only that component function and that particular instance where the event takes place is reevaluated.

State is separated on a per component instance basis.

useState manages the value of the const variable. We don’t manage it. We don’t see it.

const [title, setTitle] = useState(props.title);

We call a setTitle() function to set a new value. We never set it using an = operator. This is why we can use a const when setting title.

How to get the latest title value:

The function is re-executed when the state is updated.

const [title, setTitle] = useState(props.title);

We call setTitle() to assign a new title. This makes the component run again. The latest value of title is fetched from memory and assigned to title in

const [title, setTitle] = useState(props.title);

There is a difference between the component function running the first time and on subsequent state changes.

On subsequent changes in value using the setTitle function the useState function will return the changed value. The value that was just set.

What happens the first time?

First time the value is set from what is coming in from props.

Next time it is set using what is sent in through the useState function.

useState() returns the value and the updating function.

You call the updating function whenever the state should change.

React will re-execute the component function and the JSX code whenever the state changes.

State adds reactivity to our application. Without state our user interface would never change.

Tomorrow will do video #51 – Adding Form Inputs.

Leave a Reply

Your email address will not be published. Required fields are marked *