In this lesson we convert our AmountField class component to a function component and then convert its state from this.state
/this.setState
to the useState hook.
As in our earlier lesson we apply the following technique for migrating a class component to a function component:
class
keyword to function
and remove the extends React.Component
partrender()
method in the function bodythis.
to reference methods or variablesThe useState hook itself has an interesting API where it returns an array with two important properties: a value and a setter.
const [value, setValue] = useState(defaultValue);
Any time setValue
is called our component gets re-rendered.
Unlike the setState
API our value setter only takes a single argument, the new value.
Our example here only showed a single state value, but you can call useState
as many times as you need a component.
Jamund Ferguson: [0:02] Open up AmountField.js. At the top of the file, let's make sure that we import { useState } from "react". Now, we'll convert the class AmountField to a function component, first by typing export function AmountField, and then replacing extends with open and close parentheses.
[0:17] For now, we'll comment out our constructor function, and convert all the other methods into functions. The render() method simply becomes the body of our function component. We have to convert the onChange handler to reference our onChange function.
[0:33] Let's pull in our props. Once again, we'll destructure them here in our function declaration before we add props.amount and props.changeAmount. We'll pull both of those in as variables here.
[0:45] To replace this.state.amount, we're going to use the useState hook. Type const [displayAmount, setDisplayAmount] = useState(amount). Here, we've declared a new piece of state called displayAmount, which is initialized to the value of amount the first time our component gets rendered. When we want to update displayAmount, we use setDisplayAmount.
[1:10] First, let's update this.state.amount and replace that with displayAmount. Then, this.setState we'll replace with setDisplayAmount. The argument for setDisplayAmount is not an object, it's just a new value, in this case, newAmount. Because we haven't brought it over yet, we'll now comment out this.changeAmount.
[1:29] We can see now our component is a lot smaller than before. We export the function AmountField. Takes in two props, amount and changeAmount. We then create a piece of state, called displayAmount, and also pull off the setDisplayAmount function which we use inside of our onChange handler.
[1:46] Anytime setDisplayAmount is called, our entire component is re-rendered with the new value of displayAmount. Whatever I type in this input field, immediately shows up, which is exactly what we wanted to do.