incrementCountwhen the button is clicked. See the full list of React listener attributes here: https://reactjs.org/docs/events.html#supported-events.
incrementCountinside the component function
Counter. We would not typically define a function inside a function in JS, but this is standard convention in React functional components.
countvariable value on line 16. Clicking the button triggers
incrementCount, and the value of
countchanges, but its value on screen never does.
this.statethat is an object that stores the local state for that component. When properties in
this.statechange, the JSX that depends on those properties gets re-rendered.
this.stateis replaced by what is known as "hooks". Hooks are the more modern React system for DOM manipulation, replacing both
this.stateand what were known as "component lifecycle methods" that we will learn about in Module 8: Advanced React. The React team launched hooks in Feb 2019, thus many companies that used React before 2019 still rely on class components.
useStateis a React function that returns an array with 2 elements.
Xis the variable name from #1.
useStatetakes 1 input, the initial state value. In the example below
countgets updated when we press the button!
console.logon line 14 runs every time the counter gets updated
setCount, React takes the value and calls the component function again, where
countin the re-rendered component is the new value, but
countin the original component is still the old value. The variable
countand hook function
setCountare related from when we first created them with
useState. The subsequently called component function renders JSX with the new value and React puts it on screen.
document.getElementById('count')to get the element that displays the count, and setting that element's text value to the new count.
countstate changes. This makes our lives easier as developers because we no longer need to manually manage state; React manages it automatically for us.
countstate and re-renders
Countercomponent with new value of
countchanges. To avoid this for performance reasons, we might move
Fahrenheitcomponents up inside the
Appcomponent so that they are not re-rendered every time
setCountfunction call, the browser screen has not been updated yet.
count. It has also not changed. Calling the set state function does not set the count state variable. This value changes after the function ends.