Search code examples
laraveleloquentlaravel-livewire

Livewire Mount vs. Render


I would like to understand what is the difference between mount and render methods in Livewire components, since I have seen examples where both are used to define initial state of variables. For instance, when you instantiate a variable with records from the model, which is the right place to load the data using the ORM syntax?


Solution

  • The mount() method is what's called a "lifecycle-hook". There are a few more of these kind of methods in Livewire, which are outlined in the official documentation - https://laravel-livewire.com/docs/2.x/lifecycle-hooks - while the render() is the final method that's called to render the actual view.

    The mount() method is the construct to the component. This is where you pass in the data that the component needs. This method is only called once, on the initialization of the component, which means its also typically where you set up initial values that aren't constants.

    However, since public properties of a Livewire component can only be collections, the instance of a model, arrays or native PHP types like string and integer, you can't pass more "advanced" types that relies on a state - for example like the pagination of a query of models.

    That is why you would sometimes need to pass data to the component via the render() method, like you would when returning data in a normal Laravel controller. Another reason to pass data here is that the data is not exposed in JavaScript, like the public properties of the component is.

    The render() method is called at the end of every lifecycle request, but before the component dehydrates. Official documentation has more detailed information https://laravel-livewire.com/docs/2.x/rendering-components#render-method - the data defined here isn't a property of the class, and thereby not accessible in the other methods in the component.

    So to answer your question, it depends on what type of data you are passing, if the data should be accessible in the other methods in the class or if it's sensitive such that it shouldn't be visible in the JavaScript object attached to the component.