Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 36 ยท Getting Started

The Electron App Lifecycle and Its Events

Understand the Electron app lifecycle: ready, activate, window-all-closed, before-quit, will-quit and single-instance locking, with a runnable event-order stand-in and platform differences.

Every Electron app goes through the same stages: it starts, becomes ready, opens windows, may lose and regain focus, and finally quits. The app module emits events at each stage, and your main process code reacts to them. Getting the lifecycle right is what makes an app feel native: closing the last window quits on Windows and Linux but not on macOS, clicking a dock icon reopens a window, and a second launch focuses the existing instance instead of creating a duplicate.

The main events

Event When it fires Typical use
will-finish-launching Very early, before ready macOS file-open handlers
ready Electron has finished initializing Create windows, menus, tray
activate (macOS) Dock icon clicked Reopen a window if none exist
window-all-closed The last window closed Quit, except on macOS
before-quit Quit was requested, windows not yet closed Save state, set a "really quitting" flag
will-quit All windows closed, app is about to exit Release shortcuts, final cleanup
quit The app is exiting Last-chance logging

app.whenReady() is simply a promise version of ready. You may call it any time; if the app is already ready it resolves immediately.

flowchart TD
  A["Process starts"] --> B["will-finish-launching"]
  B --> C["ready"]
  C --> D["Windows open, app runs"]
  D --> E{"Last window closed?"}
  E -->|"yes"| F["window-all-closed"]
  F -->|"app.quit() called"| G["before-quit"]
  D -->|"Cmd+Q / app.quit()"| G
  G --> H["windows close"]
  H --> I["will-quit"]
  I --> J["quit"]

Figure: the order of the core lifecycle events.

The standard template

Most apps use a variation of this skeleton. The branches on process.platform are not decoration; they follow the conventions users expect on each system:

JavaScript
const { app, BrowserWindow } = require('electron')

app.whenReady().then(() => {
  createWindow()

  // macOS: re-create a window when the dock icon is clicked and none are open
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

// Windows and Linux: quit when the last window closes
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})

Why does this differ? On macOS, a menu bar and a dock icon stay present even without windows, so users expect to quit explicitly with Cmd+Q. On Windows and Linux, an app with no windows is invisible, which would look like a hang.

Watching the order of events

The real events depend on the operating system, but the order is deterministic. This stand-in models an app with the same event names so you can see exactly which handlers run, and in what order, for a normal quit.

Node.js Stand-in: lifecycle event order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Change platform to 'darwin' and rerun: window-all-closed still fires, but nothing quits, because the handler does not call app.quit().

Quit handlers and saving work

before-quit is the right place to flush data, because it fires while windows still exist. You can also stop the quit with event.preventDefault() (for example to ask "Save changes?"), but be careful: if you prevent the quit you must trigger it again yourself once the user decides, or the app can never exit.

JavaScript
let isQuitting = false

app.on('before-quit', (event) => {
  if (!isQuitting && hasUnsavedWork()) {
    event.preventDefault()
    askToSave().then((answer) => {
      if (answer !== 'cancel') {
        isQuitting = true
        app.quit()
      }
    })
  }
})

Use will-quit to release global shortcuts (globalShortcut.unregisterAll()) and close long-running resources such as databases. Do not start new asynchronous work there; the process may exit before it finishes.

Only one copy at a time

Many apps (chat, music, editors) should not run twice. app.requestSingleInstanceLock() returns false if another instance already holds the lock, and the first instance receives a second-instance event with the second one's command line.

JavaScript
const gotLock = app.requestSingleInstanceLock()

if (!gotLock) {
  app.quit() // we are the second instance, leave
} else {
  app.on('second-instance', (event, argv, workingDirectory) => {
    const win = BrowserWindow.getAllWindows()[0]
    if (win) {
      if (win.isMinimized()) win.restore()
      win.focus()
    }
  })

  app.whenReady().then(createWindow)
}

Here is the lock logic as a runnable stand-in. A shared object plays the role of the operating system's lock.

Node.js Stand-in: single instance lock

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Other useful lifecycle details

  • app.exit(code) quits immediately without firing before-quit or will-quit. Use it only for fatal errors.
  • app.relaunch() plus app.exit(0) restarts the app, for example after an update.
  • app.on('open-file') and app.on('open-url') (macOS) deliver files and custom-protocol links; Windows and Linux deliver them through the second-instance command line.
  • app.setLoginItemSettings() controls launch at login.
  • On macOS, app.dock lets you set a badge or hide the dock icon.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which event should you wait for before creating a BrowserWindow?

    ready fires once Electron has initialized; windows must be created after it, usually inside app.whenReady().
  2. 2. Why does the standard template skip app.quit() on macOS in window-all-closed?

    On macOS the menu bar and dock icon remain, so apps stay alive until the user quits explicitly.
  3. 3. What happens if you call event.preventDefault() in before-quit and never call app.quit() again?

    Preventing the default cancels the quit, so you must trigger app.quit() yourself once you are done.
  4. 4. What does requestSingleInstanceLock() return in a second copy of the app?

    It returns false when another instance already holds the lock; the first instance gets a second-instance event.
  5. 5. How does app.exit() differ from app.quit()?

    app.exit() terminates immediately without the normal quit events; app.quit() runs the full sequence.

Summary

  • ready is when you create windows; app.whenReady() is its promise form.
  • Handle activate (macOS) and window-all-closed (everyone else) to follow platform conventions.
  • before-quit is for saving; will-quit is for cleanup; app.exit() bypasses both.
  • Use requestSingleInstanceLock() and second-instance to avoid duplicate apps.

Next: The Main Process and Node.js