What is the difference between OnInitialized and OnParametersSet? When would you use one over the other?
Last updated
OnInitialized runs exactly once when the component is first created, while OnParametersSet runs after initialization and again every time the parent passes new parameter values. Use OnInitialized for one-time setup and OnParametersSet to react to changing inputs.
OnInitialized: Fires once per component lifetime; ideal for loading data that doesn't depend on parameters changing, wiring up subscriptions, or reading initial config.OnParametersSet: Fires after every parameter update (including the first), so it's where you recompute derived state or refetch data when a parameter like anIdchanges.The classic trap: If you load data based on a parameter only in
OnInitialized, it won't refresh when the parent reuses the same component with a new value; do that inOnParametersSet.Rule of thumb: Independent of parameters:
OnInitialized. Depends on parameters:OnParametersSet, often guarded by comparing the new value to a cached one to avoid redundant work.
- https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-10.0
- https://alexb72.medium.com/blazor-lifecycle-methods-oninitialized-onparametersset-and-onafterrender-36081a225d68
- https://blazor-university.com/components/component-lifecycles/
- https://blog.stackademic.com/mastering-the-blazor-lifecycle-when-to-use-each-method-without-losing-your-sanity-055c25d3728e
- https://www.learnblazor.com/component-lifecycle