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.