What's the difference between @computed and @action in MobX?

2.4k Views Asked by At

What's the difference between @computed and @action in MobX?

They both are functions, so what is difference between them?

2

There are 2 best solutions below

0
On BEST ANSWER

@computed is used when the function will 'compute' the return value from existing information.

@action is used for functions that will change to the existing information (state), and prompts 'observers' to access the latest version of the relevant 'observable(s)'.

0
On

The difference is stated in the documentation.

action

Usage: action(fn) or action (annotation)

Use on functions that intend to modify the state.

computed

Usage: computed(fn, options?) or computed(options?) (annotation)

Creates an observable value that is derived from other observables, but won't be recomputed unless one of the underlying observables changes.

So computed doesn't do anything other than observing the state. codesandbox

action actually modify the state. action example