The importance of state ownership in Elm
Boolean Julian Jәlfs

I think the best approach here is the one you describe in ‘Do not allow two copies of volatile data’, possibly with a slight tweak. Any approach which relies on you keeping different parts of your model state duplicated and in sync is always going to be at risk of you forgetting to do this in some way, leading to valid Elm code but with hard to track down logic bugs.

By contrast, the issues with passing down both global and page state to each page update function are that it increases the length of the update function type signature, and it also makes it inconsistent with the main update function.

I think the first issue is a strictly better problem to have than the issue with duplicating state, as any mistake you make in using these functions will be caught by the Elm compiler, which is not the case with duplicated state.

For the second issue, I think it’s worth noting that this is not really an issue at all — there is no reason that any nested ‘update’ functions have to mirror the overall update function passed to ‘Html.program’, and this may frequently be unnecessary. For instance you might have an update function for part of your app which only produces ‘Cmd Msg’s, as it is only intended to have effects and has no state; you would then use this appropriately in your main update function with an empty model.

To help mitigate having a longer function type signature you could also make a tweak to what you describe, by defining your model so that all global state is in one place:

type alias Root =
{ app: AppState
, pageOne: PageOne.Model
, pageTwo: PageTwo.Model
, pageThree: PageThree.Model
type alias AppState = {
{ user: User
-- Your page update functions could have this type signature.
update: AppState -> Msg -> Model -> (Model, Cmd Msg)

This way if you later need to add more state to be available throughout the app you could just add it to ‘AppState’ without needing to change any function signatures using this.

Nice article by the way, it made me think about this issue more.

Like what you read? Give Bob Whitelock a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.