乐闻世界logo
搜索文章和话题

When to use computed/observables in mobx

1个答案

1

In MobX, strategically selecting between computed values and observables is crucial for optimizing your application's performance and ensuring the correctness of the reactive system. I will explain their usage scenarios and provide examples:

Observables

Observables are fundamental concepts in MobX used to track changes in application state. You should define states that you want to depend on in UI or other computations as observables. These states can be simple data types such as strings and numbers, or complex data types such as objects, arrays, and maps.

Usage Scenario Example:

Assume you are developing a to-do application where users can add, delete, and mark to-dos as completed. In this case, the to-do list should be an observable because the UI needs to update when the content of the to-do list changes.

javascript
import { observable } from 'mobx'; class TodoStore { @observable todos = []; addTodo(item) { this.todos.push(item); } removeTodo(id) { this.todos = this.todos.filter(todo => todo.id !== id); } }

Computed Values

Computed values are used to automatically derive values based on existing observables. When the dependent observable values change, computed values automatically recalculate. Using computed values helps you avoid unnecessary computations and maintain data consistency.

Usage Scenario Example:

Continuing with the to-do application example, suppose you need to display the count of unfinished to-dos in the UI. This value can be derived from the todos observable, so it should be defined as a computed value.

javascript
import { computed } from 'mobx'; class TodoStore { @observable todos = []; @computed get unfinishedTodoCount() { return this.todos.filter(todo => !todo.finished).length; } }

In this example, unfinishedTodoCount is a computed value that depends on the todos observable. Whenever todos changes, unfinishedTodoCount automatically updates, ensuring that the count of unfinished to-dos displayed in the UI is always up-to-date.

Summary

  • Use observables: When you have application states whose changes need to be tracked and trigger UI updates or other side effects.
  • Use computed values: When you need to derive or compute new values from existing observables and want this value to automatically update to reflect changes in the dependent data.

Strategically using observables and computed values not only makes your application more efficient but also makes your code clearer and easier to maintain.

2024年8月16日 00:13 回复

你的答案