mobx-autorun-cleanup
TypeScript icon, indicating that this package has built-in type declarations

1.3.0 • Public • Published

mobx-autorun-cleanup

Mobx autorun function with cleanup callback

Created with TS-Standard - Typescript Standard Style Guide

Inspired By

This is very similar to the React useEffect hook.

Example

import autorunCleanup from 'mobx-autorun-cleanup'
import { observable } from 'mobx'

const obj = observable({ theme: 'light' })

const stop = autorunCleanup(() => {
  const currentTheme = obj.theme
  console.log('Load', currentTheme)
  return () => {
    console.log('Unload', currentTheme)
  }
})
// Logs: Load light

obj.theme = 'dark'
// Logs:
// Unload light
// Load dark

// If you want
stop()
// Logs: Unload dark

Differences with mobx built-in reaction

mobx-autorun-cleanup is actually very similar to reaction, which is part of mobx.

Feature reaction mobx-autorun-cleanup
Fn gets called first time ✔️
Fn is called after reactions ✔️ ✔️
Cleanup after reactions ✔️ ✔️
Cleanup after stopped ✔️
Cleanup is optional ✔️ ✔️
Separated code for reactions and side effects ✔️

Here is the same example, but it uses reaction instead of mobx-autorun-cleanup:

import { observable, reaction } from 'mobx'

const obj = observable({ theme: 'light' })

console.log('Load', obj.theme)
// Logs: Load light

const stop = reaction(() => obj.theme, (currentTheme, previousTheme) => {
  console.log('Unload', previousTheme)
  console.log('Load', currentTheme)
})
// Nothing is called until `obj.theme` is changed

obj.theme = 'dark'
// Logs:
// Unload light
// Load dark

// If you want
stop()
// Nothing is logged, because there is no cleanup fn
// You can now specify to unload
console.log('Unload', obj.theme)
// Logs: Unload dark

How to choose between the two

One way to think about the lifetime of the function and cleanup function is like a sandwich:

  • The first bread is when the function gets initially called
  • The stuff inside is when the function gets re-run after a reaction
  • The last bread is when the reaction is stopped

reaction only calls the function in the middle of the sandwich. mobx-autorun-cleanup additionally calls the function initially, and calls the cleanup function in the end.

Based on this comparison, you can decide which function to use. I think generally reaction is for side effects, and mobx-autorun-cleanup is for cleanup.

Typedoc

https://chocolateloverraj.github.io/mobx-autorun-cleanup

Readme

Keywords

none

Package Sidebar

Install

npm i mobx-autorun-cleanup

Weekly Downloads

8

Version

1.3.0

License

MIT

Unpacked Size

6.9 kB

Total Files

7

Last publish

Collaborators

  • programmerraj