Understanding the Elm Architecture

In today's episode, we will focus on one important aspect about Elm: The Elm Architecture. We have built one simple program in Elm. We also know how to integrate our code with some Elm libraries. This is a good start!

From our last program, there is one line we didn't discuss yet:

main =
    Html.beginnerProgram { model = model, view = view, update = update }

Why should my Elm code have model, view and update?

The Elm Architecture

Elm programs have this standard that is based on model, view and a function to update. If you know the MVC pattern, this is a bit similar.

The first thing we do when we write an Elm program is to have and register these three pieces.

main =
    Html.beginnerProgram { model = model, view = view, update = update }

There is only one parameter, the recording containing these three fields and the order doesn't matter, you can pass first the update function or the view,for example.

The view function returns HTML. Here is where we define what our rendered program will look like. The elm runtime makes sure the DOM always matches what our view function returns, using a virtual DOM to make it fast.

The update function updates our state - surprise! This function receives a Msg and our Model. Normally in this function we have a case statement where we handle each possible Msg in our Msg Union type.

The model function completely describes any state that can change in our application. In our last code, our model was just a number, but it can be anything, it's frequently normally an Elm record.

Making a comparison with Redux

If you have used Redux, you might think this is similar. Redux was influenced by Elm.

Our update function is like a reducer in a common redux application. The place where our state can be changed.

Our model is our state in a common redux application.

Our view will be the place where it emits or dispatches the actions using our update function.

At a glance

In this episode, we saw Elm apps use three important functions -model, view and update - to describe a program.

Resources