Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elm vs React: why no lifecycle functions in Elm?

Tags:

reactjs

elm

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?

like image 686
Robert Avatar asked Mar 04 '23 21:03

Robert


1 Answers

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.
like image 66
SolarBear Avatar answered Mar 07 '23 08:03

SolarBear