Next, we are going to migrate the AddTodo component. Here, we are going to use a State Hook to handle the input field state.
Let's migrate the AddTodo component now:
- Edit src/AddTodo.js and adjust the import statement to import the useState Hook from React:
import React, { useState } from 'react'
- Remove the class component code. We are going to define a function component instead now.
- First, we define the function, which accepts only one prop—the addTodo function:
export default function AddTodo ({ addTodo }) {
- Next, we define a State Hook for the input field state:
const [ input, setInput ] = useState('')
- Now we can define the handler functions for the input field and the add button:
function handleInput (e) {
setInput(e.target.value)
}
function handleAdd () {
if (input) {
addTodo(input)
setInput('')
}
}
- Finally, we return and render the input field and the add button:
return (
<form onSubmit={e => { e.preventDefault(); handleAdd() }}>
<input
type="text"
placeholder="enter new task..."
style={{ width: 350, height: 15 }}
value={input}
onChange={handleInput}
/>
<input
type="submit"
style={{ float: 'right', marginTop: 2 }}
disabled={!input}
value="add"
/>
</form>
)
}
As we can see, using the State Hook makes state management much simpler. We can define a separate value and setter function for each state value, instead of having to deal with a state object. Furthermore, we do not need to destructure from this.state all the time. As a result, our code is much more clean and concise.