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:
- Edit src/TodoList.js, and remove the following import statement:
import { inject, observer } from 'mobx-react'
- 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'
- 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 () {
- Again, we use the Todo Store Hook to get the todoStore object:
const todoStore = useTodoStore()
- 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.