Migrating the TodoList component

Next, we are going to migrate the TodoList component, which wraps the TodoItem component. Here, we use a context, which means that we can now use a Context Hook.

Let's migrate the TodoList component now:

  1. Edit src/TodoList.js and import the useContext Hook from React:
import React, { useContext } from 'react'
  1. Remove the class component code. We are going to define a function component instead now.
  2. We start by defining the header of our function. In this case, we do not destructure props, but simply store them in a props object:
export default function TodoList (props) {
  1. Now we define the Context Hook:
    const items = useContext(StateContext)
  1. Finally, we return the list of rendered items, passing the item and props objects to it using destructuring:
    return items.map(item =>
<TodoItem {...item} {...props} key={item.id} />
)
}
We define the key prop last, in order to avoid overwriting it with the destructuring of the item and props objects.

As we can see, using contexts with Hooks is much more straightforward. We can simply call a function, and use the return value. No magical assignment of this.context or wrapper hell when using multiple contexts!

Furthermore, we can see that we can gradually migrate components to React Hooks, and our app will still work. There is no need to migrate all components to Hooks at once. React class components can work well together with function React components that use Hooks. The only limitation is that we cannot use Hooks in class components. Therefore, we need to migrate a whole component at a time.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.54.63