Saturday, 6 February, 2021 UTC


Summary

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](https://reactjs.org/docs/hooks-state.html) hook. As in our earlier lesson we apply the following technique for migrating a class component to a function component: 1. Change the `class` keyword to `function` and remove the `extends React.Component` part 2. Place the contents of the `render()` method in the function body 3. Convert all other methods on the class to stand-alone functions 4. Remove the constructor function 5. Inline any props into the function declaration using object destructuring 6. Get rid of any use of `this.` to reference methods or variables The 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.