Course lesson
Migrate React Component State to the useState Hook
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.
- Duration
- 2 min
- Access
- Free
- Transcript
- Available
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:
- Change the
classkeyword tofunctionand remove theextends React.Componentpart - Place the contents of the
render()method in the function body - Convert all other methods on the class to stand-alone functions
- Remove the constructor function
- Inline any props into the function declaration using object destructuring
- 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.