Discover how one simple function can save you from repeating the same data loading code everywhere!
Why Layout load functions in Svelte? - Purpose & Use Cases
Imagine building a website where every page needs to fetch user data, settings, and preferences before showing anything.
You try to load this data manually on each page, repeating the same code everywhere.
Manually fetching data on every page is tiring and error-prone.
You might forget to load something, causing broken pages or inconsistent data.
It also slows down your work because you repeat the same steps again and again.
Layout load functions in Svelte let you fetch data once for a whole layout shared by many pages.
This means you write the loading code just once, and all pages inside that layout get the data automatically.
async function load() {
const user = await fetch('/api/user').then(res => res.json());
const settings = await fetch('/api/settings').then(res => res.json());
return { user, settings };
}
// Repeat this in every pageexport const load = async () => {
const user = await fetch('/api/user').then(res => res.json());
const settings = await fetch('/api/settings').then(res => res.json());
return { user, settings };
};
// Put this once in layout load functionYou can share data loading logic across many pages easily, making your app faster to build and more consistent.
Think of a dashboard app where user info and theme settings load once in the main layout, so every page inside shows the right user name and colors without extra code.
Manual data fetching on every page is repetitive and error-prone.
Layout load functions let you fetch data once for many pages.
This saves time and keeps your app consistent and clean.