5

I have built a couple of apps in Elm and now have built a couple in React.

In React I am offered functions like shouldComponentUpdate for when I might want to render a component less often.

It is only now that I am thinking: how come Elm does not have (or need) them?

1
  • 3
    Side note: With React Hooks, you typically don't need lifecycle methods anymore.
    – TrueWill
    Commented Jun 7, 2019 at 18:50

1 Answer 1

7

For the specific problem of re-rendering, out of the box Elm uses virtual DOM diffing: if its virtual DOM changed, the real DOM gets updated accordingly. This is much cheaper than working directly on the DOM.

Interestingly, Elm's behavior when using Html.lazy is the same as React's when you define components as functions (ie. not an object from a class inheriting from Component or PureComponent): since you do not rely on side effects (lifecycle functions being one appropriate example), given the same function inputs, your component will always produce the same output. This way, Elm or React only needs to re-render your component if its inputs somehow change. So, in this way, you don't have to care about whether your component needs to be re-rendered: Elm takes care of that.

So, what about these lifecycle methods? For instance:

  • shouldComponentUpdate: as I mentioned above, when using Html.lazy, Elm checks whether your input changed: if it didn't, re-rendering is clearly not needed in a functional context. Otherwise, Elm will diff its virtual DOM. In both cases, though, Elm does not need to be told whether rendering is needed or not.
  • componentWillReceiveProps: corresponds pretty much to your update function.
  • componentDidMount: I don't think there's an equivalent to this one: either you component exists and gets rendered or it does not. This is very much like using a function as a component.
2
  • 6
    Elm doesn't automatically check whether the input has changed. It checks whether the output has changed, through diffing of the virtual dom. In order to run a view function only if the input has changed, if the rendering code itself is expensive, you have to use Html.Lazy. See guide.elm-lang.org/optimization/lazy.html
    – glennsl
    Commented Jun 7, 2019 at 21:57
  • 1
    Thank you @glennsl, I mixed the lazy behavior with the vanilla one. I have updated my answer accordingly.
    – SolarBear
    Commented Jun 10, 2019 at 12:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.