The Elm Architecture (TEA)
In 2015, the JavaScript ecosystem is a bit of a wild west. We have React, but we're still figuring out how to manage state. Enter Elm, a purely functional language that compiles to JS and introduces The Elm Architecture (TEA). This pattern is so effective that it's already inspiring libraries like Redux.
The Three Pillars
TEA consists of three parts:
- Model: The state of your application.
- Update: A way to update your state.
- View: A way to view your state as HTML.
A Simple Counter in Elm
import Html exposing (Html, button, div, text)
import Html.Events exposing (onClick)
-- MODEL
type alias Model = Int
initialModel : Model
initialModel = 0
-- UPDATE
type Msg = Increment | Decrement
update : Msg -> Model -> Model
update msg model =
case msg of
Increment -> model + 1
Decrement -> model - 1
-- VIEW
view : Model -> Html Msg
view model =
div []
[ button [ onClick Decrement ] [ text "-" ]
, div [] [ text (toString model) ]
, button [ onClick Increment ] [ text "+" ]
]
main =
Html.beginnerProgram { model = initialModel, view = view, update = update }
No Runtime Exceptions
Because Elm is statically typed and doesn't allow null or undefined, your app is guaranteed to be free of runtime exceptions. If it compiles, it works.
The Secret: Immutability
Every time update is called, it doesn't modify the model. It returns a new model. The Elm runtime then takes this new model, calls view, and efficiently diffs the Virtual DOM to update the real DOM.
In 2015, Elm is the most disciplined way to build web interfaces. Even if you don't use Elm, understanding TEA will make you a better React developer.
Aunimeda designs and builds scalable software architectures - from system design to implementation and ongoing engineering.
Contact us to discuss architecture for your project. See also: Custom Software Development, Web Development