Using Hooks for the TodoList component

Next, we are going to upgrade our TodoList component. Additionally, we are also going to use the useObserver Hook, which replaces the observer higher-order component.

Let's use Hooks for the TodoList component now:

  1. Edit src/TodoList.js, and remove the following import statement:
import { inject, observer } from 'mobx-react'
  1. Then, import the useObserver Hook from mobx-react and the useTodoStore Hook from our hooks.js file:
import { useObserver } from 'mobx-react'
import { useTodoStore } from './hooks'
  1. Now, remove the inject and observer functions that are wrapping the TodoList component, and also remove all props. The TodoList function definition should now look as follows:
export default function TodoList () {
  1. Again, we use the Todo Store Hook to get the todoStore object:
    const todoStore = useTodoStore()
  1. Finally, we wrap the returned elements with the useObserver Hook. Everything within the Observer Hook will be recomputed when the state that is used within the Hook changes:
    return useObserver(() =>
todoStore.filteredTodos.map(item =>
<TodoItem key={item.id} item={item} />
)
)
}

In our case, MobX will detect that the observer that was defined via the useObserver Hook depends on todoStore.filteredTodos, and filteredTodos depends on the filter and todos values. As a result, the list will be re-rendered whenever either the filter value or the todos array changes.

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

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