Phoenix LiveView hot reload has an option to preserve socket state

Sorry if it’s a common knowledge, but it’s something I just learned and wanted to share.

I’ve seen that mind-blowing demo of hot-reload in production recently presented by Chris. So I asked if we could have something like that in development as well: Jakub Skałecki 🚀 #buildinpublic on X: "Hey @chris_mccord could we have this in development? 🧐 Right now state is not preserved across hot reloads" / X

It turns out, it’s there already! In your dev.exs Endpoint config add live_reload: notify section and update live_reload: patterns to match this:

# Watch static and templates for browser reloading.
config :my_app, MyAppWeb.Endpoint,
  live_reload: [
    notify: [
      live_view: [
        ~r"lib/my_app_web/core_components.ex$",
        ~r"lib/my_app_web/(live|components)/.*(ex|heex)$"
      ]
    ],
    patterns: [
      ~r"priv/static/(?!uploads/).*(js|css|png|jpeg|jpg|gif|svg)$",
      ~r"lib/my_app_web/controllers/.*(ex|heex)$"
    ]
  ]

Now when you update your live view code, your state will stay intact.

For me it’s a life-changer. I have to admit I wasted so much time without that feature :smiling_face_with_tear: Mostly when working with a bit more complex Live Views with forms or ephemeral state.

Did you know about it? Is it highlighted somewhere in the documentation / installation instructions but I just somehow missed it? :thinking:

23 Likes