# Higher Order Components
Source: https://docs.hana.leafphp.dev/auth/hocs
Mintlify gives you complete control over the look and feel of your documentation using the docs.json file
HOCs are functions that take in a component and return a new component with additional functionality. Hana Auth provides 2 HOCs that can be used to set/verify auth states for particular routes. These are:
* `withAuthState`
* `withGuestState`
## **withAuthState**
This HOC is used to verify that the user is authenticated before rendering the component. If the user **is not authenticated**, the user is redirected to the login page.
\_The redirect paths can be configured using the \_`loginPath`*and \_ `dashboardPath`*options as described \_ [***here***](/auth/index)*.*
```tsx theme={"theme":"ayu-dark"}
import { withAuthState } from '@hanabira/auth';
const Dashboard = () => {
return
Dashboard
;
};
export default withAuthState(Dashboard);
```
This will automatically handle redirects for you, but there is more you can do with this HOC. `withAuthState` also automatically passes the `user`, `token` and `refreshToken` props together with their setter functions and a `logout()` function to your component. This means that you can access the user and token information in the component.
```tsx theme={"theme":"ayu-dark"}
import { withAuthState } from '@hanabira/auth';
const Dashboard = ({ user, token, refreshToken, setUser, setToken, setRefreshToken, logout }) => {
console.log(user, token, refreshToken);
return (
);
};
export default withAuthState(Dashboard);
```
If you're ever in a situation where you need to update the state of the user or tokens, you can use the setter functions to do that.
```tsx theme={"theme":"ayu-dark"}
import { withAuthState } from '@hanabira/auth';
const Dashboard = ({ user, token, refreshToken, setUser, setToken, setRefreshToken, logout }) => {
const updateUser = () => {
setUser({ name: 'John Doe' });
};
const updateToken = () => {
setToken('new-token');
};
const updateRefreshToken = () => {
setRefreshToken('new-refresh-token');
};
return (
);
};
```
\*\*A general rule of thumb is to always \*\*`withAuthState`**to wrap your components that require authentication.**
## **withGuestState**
This HOC is used to verify that the user is not authenticated before rendering the component. If the user **is authenticated**, the user is redirected to the "dashboard" page.
\_The redirect paths can be configured using the \_`loginPath`*and \_ `dashboardPath`*options as described \_ [***here***](/auth/index)*.*
```tsx theme={"theme":"ayu-dark"}
import { withGuestState } from '@hanabira/auth';
const Login = () => {
return
Login
;
};
export default withGuestState(Login);
```
`withGuestState()` automatically passes the `login()` function to your component. This function allows you to change the auth state of the user to authenticated and save the user information.
```tsx theme={"theme":"ayu-dark"}
import { withGuestState } from '@hanabira/auth';
const Login = ({ login }) => {
return (
Login
);
};
export default withGuestState(Login);
```
This `login()` function takes in an object with the following properties:
* `user`: The user information to save.
* `token`: The token to save.
* `refreshToken`: The refresh token to save.
A general rule of thumb is to always use `withGuestState()` to wrap your components that require the user to be unauthenticated.
# Hooks
Source: https://docs.hana.leafphp.dev/auth/hooks
Auth hooks for your app
There are 2 main auth states: authenticated and unauthenticated. Hana Auth provides 2 hooks that can be used to set/verify auth states for particular routes. These are:
* `useAuthState`
* `useGuestState`
## useAuthState()
This hook is used to verify that a user is authenticated. If the user is not authenticated, they will be redirected to the login page. If the user is authenticated, this hook will return an object containing the user, tokens and their setters as well as a `logout()` function.
```tsx theme={"theme":"ayu-dark"}
import { useAuthState } from '@hanabira/auth';
const MyComponent = () => {
const { user, token, refreshToken, logout } = useAuthState();
return (
{user.name}
)
}
```
Sometimes, you might need to update the user's information after they have logged in. For example, you might want to replace the user's details after they update their profile. For this, the `useAuthState` hook also returns `setUser`, `setToken` and `setRefreshToken` functions that can be used to update the user's information.
```tsx theme={"theme":"ayu-dark"}
import { useAuthState } from '@hanabira/auth';
const MyComponent = () => {
const { user, setToken, setRefreshToken, setUser } = useAuthState();
const updateUser = async () => {
const updatedUser = await fetch('/api/user');
setUser(updatedUser);
};
const updateToken = async () => {
const updatedToken = await fetch('/api/token');
setToken(updatedToken.token);
setRefreshToken(updatedToken.refreshToken);
};
return (
{user.name}
);
};
```
## useGuestState()
This hook is used to verify that a user is unauthenticated. If the user is authenticated, they will be redirected to the home page. If the user is unauthenticated, this hook will return an object containing a `login()` function. This function takes in an object containing the user and tokens and sets them in the appropriate storage.
```tsx theme={"theme":"ayu-dark"}
import { useGuestState } from '@hanabira/auth';
const MyComponent = () => {
const { login } = useGuestState();
const handleLogin = async () => {
const res = await makeLoginRequest();
login({
user: res.user,
token: res.token,
refreshToken: res.refreshToken
});
}
return (
);
}
```
## **useLogin**
Although `useGuestState` provides a `login()` function, it is not always convenient to use it. For example, if you have a complex authentication sytem, you might want to be able to login from other components. For this, Hana Auth provides a `useLogin` hook that can be used to login a user.
```tsx theme={"theme":"ayu-dark"}
import { useLogin } from '@hanabira/auth';
const MyComponent = () => {
const login = useLogin();
const handleLogin = async () => {
const res = await makeLoginRequest();
login({
user: res.user,
token: res.token,
refreshToken: res.refreshToken
});
}
return (
);
}
```
The `login()` function in the example above will automatically redirect the user to the home page after they have been logged in. If you however have an operation that you want to perform after the user has been logged in, you can usethe `login()` function as a promise. You can also pass in a `redirect` option to the `login()` function to make sure the redirect does not happen.
```tsx theme={"theme":"ayu-dark"}
import { useLogin } from '@hanabira/auth';
const MyComponent = () => {
const login = useLogin();
const handleLogin = async () => {
const res = await makeLoginRequest();
login({
user: res.user,
token: res.token,
refreshToken: res.refreshToken,
redirect: false
})
.then(() => {
// Do something after the user has been logged in
});
}
return (
);
}
```
## **useLogout**
This hook is used to logout a user. It clears the user and tokens from the appropriate storage and redirects the user to the login page.
```tsx theme={"theme":"ayu-dark"}
import { useLogout } from '@hanabira/auth';
const MyComponent = () => {
const logout = useLogout();
return (
);
}
```
The `logout()` function in the example above will automatically redirect the user to the login page after they have been logged out. If you however have an operation that you want to perform after the user has been logged out, you can usethe `logout()` function as a promise. You can also pass in a `redirect` option to the `logout()` function to make sure the redirect does not happen.
```tsx theme={"theme":"ayu-dark"}
import { useLogout } from '@hanabira/auth';
const MyComponent = () => {
const logout = useLogout();
const handleLogout = async () => {
logout({ redirect: false })
.then(() => {
// Do something after the user has been logged out
});
}
return (
);
}
```
## **useUser**
This hook is used to get the user's information. It returns the user's information if the user is authenticated. The returned object contains the user, tokens and their setters.
```tsx theme={"theme":"ayu-dark"}
import { useUser } from '@hanabira/auth';
const MyComponent = () => {
const { user, token, refreshToken } = useUser();
return (
{user.name}
);
}
```
## **getAuth**
You might be in a situation where you need to get the user's information outside of a component. For example, you might need to get the user's information or tokens in a utility function. For this, Hana Auth provides a `getAuth` function that can be used to get the user's information.
```tsx theme={"theme":"ayu-dark"}
import { getAuth } from '@hanabira/auth';
const someCrazyAction = () => {
const { user, token, refreshToken } = getAuth();
return doSomething({
user,
token,
refreshToken,
});
}
```
# Authentication
Source: https://docs.hana.leafphp.dev/auth/index
Automatic token & auth state management
SPAs usually handle authentication via tokens, with checks to find if the token exists, and rugged middleware that maintains the current state or invalidates the state depending on responses from the backend.
Hana ships an authentication component powered by Hana Auth that automatically takes care of all of that. All you need to do is pass in your user, and Hana will take care of the rest.
Hana Store is automatically added to projects generated using `create-hana-app`, but you can manually install it from npm
```bash theme={"theme":"ayu-dark"}
npm install @hanabira/auth
```
## **Getting started**
After installing Hana Auth, the first thing to do is to initialize your authentication using the `createAuth` function.
```tsx src/pages/_app.tsx theme={"theme":"ayu-dark"}
import { createAuth } from '@hanabira/auth';
createAuth();
```
This function takes in an optional config object that can be used to configure the auth utility. It is recommended to call this function in your root component so that it is only called once.
## **Auth Configuration**
The config object has the following properties:
* `tokenKey`: The key to use when saving the token to local storage. Defaults to `token`.
* `userKey`: The key to use when saving the user to local storage. Defaults to `user`.
* `refreshTokenKey`: The key to use when saving the refresh token to local storage. Defaults to `refreshToken`.
* `loginPath`: The path to redirect to when the user is not authenticated. Defaults to `/login`.
* `logoutPath`: The path to redirect to when the user logs out. Defaults to `/login`.
* `dashboardPath`: The path to redirect to when the user is authenticated. Defaults to `/dashboard`.
* `cookie`: Options to use when saving information to a cookie.
```tsx theme={"theme":"ayu-dark"}
import { createAuth } from '@hanabira/auth';
...
createAuth({
tokenKey: 'token',
userKey: 'user',
refreshTokenKey: 'refreshToken',
loginPath: '/login',
dashboardPath: '/dashboard',
});
```
## **Authentication types**
The auth utility provides different types of authentication. These types are:
* `localstorage`: This type of authentication uses the browser's local storage to save the token and user information. This is the default type of authentication.
* `cookie`: This type of authentication uses cookies to save the token and user information.
Auth with local storage is the default type of authentication. To use cookie authentication, you need to pass in the `cookie` option to the `createAuth` function.
```tsx theme={"theme":"ayu-dark"}
import { createAuth } from '@hanabira/auth';
createAuth({
cookie: {
path: '/',
expires: 60,
domain: 'localhost',
sameSite: 'Lax',
},
});
```
The `cookie` option takes in the following properties:
* `path`: The path where the cookie is available. Defaults to `/`.
* `expires`: Define when the cookie will be removed. Value can be a Number which will be interpreted as days from time of creation or a Date instance. If omitted, the cookie becomes a session cookie.
* `domain`: Define the domain where the cookie is available. Defaults to the domain of the page where the cookie was created.
* `sameSite`: Asserts that a cookie must not be sent with cross-origin requests,providing some protection against cross-site request forgery attacks (CSRF)
* `secure`: A boolean indicating if the cookie transmission requires a secure protocol (https). Defaults to false.
From here, everything else is the same as local storage authentication.
## **Auth states**
Generally, there are two auth states: authenticated and unauthenticated. When the user is authenticated, the auth utility saves the token and user information to the appropriate storage. This information is then used to verify the auth state of the user and is removed when the user logs out. Hana Auth provides multiple ways to change and verify the auth state of the user.
# Hana: React without overengineering
Source: https://docs.hana.leafphp.dev/index
The modern web is unnecessarily complex, everything is over-engineered
Everything from wrestling with SSR and server components to annoying hydration quirks and config wars. Devs from all over the world see these patterns as a burden, not a feature.
> “React has evolved … into a sprawling ecosystem thought to hinder performance.”\
> — from blog *JavaScript Fatigue Strikes Back*
If your goal is to build front ends fast and ship UI, not infrastructure, Hana was made for you
## What Hana gives you **out of the box**
Hana gives you:
* A **built-in router** with file-based conventions
* A **global state system** that’s simple and flexible
* **Auth / session helpers** out of the box
* **Zero config**, low friction (powered by Vite)
* **Modular adoption** let's you use just the router, the store, auth, or all of them
```tsx theme={"theme":"ayu-dark"}
import { Link } from '@hanabira/router';
import { useStore } from '@hanabira/store';
import { withAuthState } from '@hanabira/auth';
const Dashboard = ({ user, logout }) => {
const [item, setItem] = useStore('item');
return (
About
Hello, {user.name}
);
};
export default withAuthState(Dashboard);
```
Think of Hanabira as: React + routing + state + auth. The very basics, no overreach. What's more, you can incrementally add or remove pieces of Hana on demand, so there's no need to cram the whole framework
Let's generate your first app in just 2 minutes
## Already have a vite app?
If you already have a React app running on Vite, you can incrementally adopt Hana's modules into your app. This gives you the flexibility to keep your app working as-is, while slowly switching to all the goodies Hana gives you.
Set up a global store in your application for easy access to data from any component
Take advantage of file-based routing powered by React Router with no setup
Let Hana take care of the annoying parts of authentication like middleware & config
Install Hana Utils for access to everyday features like caching & data fetching
## What Hana *doesn't* do (by design)
Hana may not be as powerful as other meta-frameworks like Next, but it doesn't have to be. We carefully crafted Hana, avoiding all the chaos of the modern web out of the box
* **No SSR / SSG** because we believe client rendering is sufficient for many apps
* **No server components / hybrid rendering** so you control when to fetch / render
* **No hidden abstractions / magic** which means everything is explicit, understandable
Hana has worked for us and businesses serving **2M+ customers**, so let's **stop overengineering**, and start **shipping UI** 💜
# Quickstart
Source: https://docs.hana.leafphp.dev/quickstart
Let's build an amazing app in just 2 minutes
**Prerequisites**:
* Node.js version 18 or higher
* Anywhere Vite can run
Hana is built by design to be simple to integrate into any project. At it's core, Hana is just a simple Vite and React setup, and we've got a superfast way to get you set up using your favourite package manager.
```bash theme={"theme":"ayu-dark"}
npm create hana-app@latest # for npm users
yarn create hana-app@latest # for yarn users
pnpm create hana-app@latest # for pnpm users
```
This will walk you through a series of prompts to help set up your project
Navigate to the generated project, and start the vite server:
```bash theme={"theme":"ayu-dark"}
npm run dev
```
A local preview of your documentation will be available at `http://localhost:3000`.
## Install in existing Vite app
If you already have a React app running through Vite, Hana's modular approach allows you to pick any piece, and install it into your app for a gradual adoption experience.
```bash theme={"theme":"ayu-dark"}
pnpm install @hanabira/
```
Every Hana module can be installed as a standalone package, so just head over to the documentation for the functionality you need and run the install script
Most Hana modules can be used right on install, but if you need to do any config, you can follow the config guide tied to the module you want to use. For example, we can set default values and save our global state to sessionStorage
```typescript theme={"theme":"ayu-dark"}
import { createStore, PersistedState } from '@hanabira/store';
createStore({
state: {
updated: false
},
plugins: [
new PersistedState({
storage: window.sessionStorage,
exclude: ['rates'],
}),
],
});
```
Every module will include its own config/setup guide
## Next steps
Now that you have your application running, explore these key features:
Set up a global store in your application for easy access to data from any component
Take advantage of file-based routing powered by React Router with no setup
Let Hana take care of the annoying parts of authentication like middleware & config
Install Hana Utils for access to everyday features like caching & data fetching
**Need help?** Join our [community](https://discord.gg/Pkrm9NJPE3) to receive help from existing users
# Router Config
Source: https://docs.hana.leafphp.dev/routing/config
Add extra options to Hana router for your app
Hana router is already configured for you right out of the box, but you can add a few options to change the functionality to match your application's exact specs. Configuration can be done through the hana vite plugin in your vite config file
## Application Pages Directory
This is where Hana will load your routes from, and defaults to `src/pages`
```ts theme={"theme":"ayu-dark"}
import { defineConfig } from 'vite';
import { hana } from '@hanabira/router';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
export default defineConfig({
plugins: [
react(),
tailwindcss(),
hana({
pages: 'app'
}),
],
});
```
This config above changes the pages directory to the `app` folder, so your routes will look like `app/home/index.tsx`
## TypeScript Support
You can toggle TS support using the `typescript` config option:
```ts theme={"theme":"ayu-dark"}
hana({
typescript: true
}),
```
## Lazy Route Loading
Hana automatically applies lazy loading to all your routes, which helps reduce bundle sizes and improves the overall performance of your app especially over not-so-good connections. You can toggle this using the `useLazy` option
```ts theme={"theme":"ayu-dark"}
hana({
useLazy: true
}),
```
## Router Mode
Hana supports history and hash mode for routing, and you can select the option you prefer using the `mode` key
```ts theme={"theme":"ayu-dark"}
hana({
mode: 'hash'
}),
```
# Dynamic Routing
Source: https://docs.hana.leafphp.dev/routing/dynamic
Create routes on demand from dynamic data
Dynamic routing is the idea of creating routes that aren't fixed. For example, leaf's [x.com](http://x.com) profile is x.com/leafphp, but yours is x.com/username. Since there's no real way for X to know what username you'd set, your profile link can't be hardcoded, and so we call that a dynamic route.
## Creating dynamic routes
Hana routes are tied to files, so you might be wondering how we can build a url like `/users/id` where id is the dynamic part. For cases like that, the file/folder name should be wrapped in `[]` , so in this case the file name could be made like this:
* **users/\[id].tsx** -> /users/\[id]
* **users/\[id]/index.tsx** -> /users/\[id]
And the dynamic part of the url can be accessed via the `useParams()` hook:
```tsx src/pages/users/[id].tsx theme={"theme":"ayu-dark"}
import { useParams } from '@hanabira/router';
export default function User() {
const { id } = useParams();
return
User ID: {id}
}
```
Note that the name of the dynamic section is used as the name of the parameter you'll access through `useParams()` so each dynamic URL section should be unique.
## **Nested Dynamic Routes**
You can create a dynamic route consisting of more than one dynamic section. For example, you can create a route that accepts a user id and a post id, and for such cases, we can utilize the dynamic section as the folder name.
```tsx src/pages/users/[user]/posts/[id].tsx theme={"theme":"ayu-dark"}
import { useParams } from '@hanabira/router';
export default function Post() {
const { user, id } = useParams();
return (
User: {user}
Post ID: {id}
)
}
```
## **Dynamic Routes with Query Parameters**
This is not an unusual combination, as query parameters can themselves be used for dynamic routing. We can combine query parameters with dynamic url segments to make urls like this: `https://example.com/feed/userid?post=postId`
```tsx src/pages/feed/[userId].tsx theme={"theme":"ayu-dark"}
import { useParams, useQueryParams } from '@hanabira/router';
export default function User() {
const { userId } = useParams();
const { post } = useQueryParams();
return (
User ID: {id}
Post: {post}
)
}
```
## **Optional Dynamic Routes**
Optional dynamic routes are dynamic routes that can be accessed with or without a parameter. This can be done by wrapping the parameter in double square brackets (`[[]]`). For example, if you create a file called `[[query]].tsx` in the `pages/search` directory, it will create a route for `/search/[[query]]`. This route will be accessible on `/search` and `/search/:query`. You can then access the query parameter using the `useParams` hook.
```tsx src/pages/search/[[query]].tsx theme={"theme":"ayu-dark"}
import { useParams } from '@hanabira/router';
export default function Search() {
const { query } = useParams();
return
Query: {query ?? 'nothing'}
}
```
# Errors
Source: https://docs.hana.leafphp.dev/routing/errors
Customize error screens
Hana router provides default error pages for 404 and 500 errors, however, we recommend updating them with your own custom pages
## 404 Pages
When a user enters a route that doesn't exist in your app, Hana will look for a `_404` file, and render the component exported from that file.
```tsx src/pages/_404.tsx theme={"theme":"ayu-dark"}
const NotFound: React.FC = () => {
return
404 - Not Found
;
};
export default NotFound;
```
## General Error Pages
When an error is thrown within your application, Hana will catch the error and display whatever component is in your `_error` file.
```tsx src/pages/_error.tsx theme={"theme":"ayu-dark"}
import { useRouteError } from "@hanabira/router";
export default function ErrorPage() {
const error: any = useRouteError();
console.log(error, 'error');
return
Error
;
}
```
Usually your application will only have one error page, however, Hana allows you to create error pages scoped to only particular folders. For example, you can have a `_error.tsx` file in the `pages/users` directory that will be used for all errors that occur on routes in the `/users` directory.
```
|- pages
|- index.tsx
|- _error.tsx
|- users
|- _error.tsx
```
Considering the directory structure above, the `_error.tsx` file in the `pages/users` directory will be used for all errors that occur on routes in the `/users` directory. The `_error.tsx` file in the `pages` directory will be used for all other errors.
# Hana Router
Source: https://docs.hana.leafphp.dev/routing/index
Incredibly powerful file-based routing powered by React Router
Amid the chaos of overcomplicated tech, file-based routing turned out to be a nice addition for a few reasons:
* No need to think about what router to use
* Creating a new route in a specified directory automatically creates a route
* No need to create a route map, handle children and all of that
* Layouts, loading states and route props automatically handled by router
## Getting Started
Hana Router is automatically added to projects generated using `create-hana-app`, but if you already have a React project running Vite, you can easily add the router to your project.
```bash theme={"theme":"ayu-dark"}
npm install @hanabira/router
```
Open your Vite config file and add the Hana plugin with optional config
```typescript theme={"theme":"ayu-dark"}
import { defineConfig } from 'vite';
import { hana } from '@hanabira/router';
import react from '@vitejs/plugin-react';
export default defineConfig({
plugins: [
react(),
hana({
root: __dirname,
typescript: true,
usePageTransition: true,
mode: 'history',
}),
],
});
```
A local preview of your documentation will be available at `http://localhost:3000`.
The next step is to create an `src/pages` folder which will hold all your routes.
**If** **you feel the need to** have a root file which you can use for initializing libraries like swr, react query or toast libraries, then you can create an `src/pages/_app.(jsx/tsx)` file which accepts a bunch of children and displays them
```tsx theme={"theme":"ayu-dark"}
const App = ({ children }) => {
return <>{children}>;
};
export default App;
```
Every Vite project ships with an `index.html` file which loads the entire application. To switch your application to Hana router, you need to update the entry script to `.hana/_app.tsx`, don't worry this script will be automatically created by hana on build/dev
```html theme={"theme":"ayu-dark"}
Vite + React + TS
```
And....that's it!
As mentioned, Hana uses file-based routing, which means creating a file in the pages directory will automatically add a new route for you. For example, let's add an `src/pages/home.tsx` file:
```tsx home.tsx theme={"theme":"ayu-dark"}
export default function Home() {
return
Hello World
}
```
You will imediately be able to access this page by visiting `/home` in your browser. It's that straightforward. Hana will use the slugified version of the file name as the route name without the extension.
## **Ignored Files**
We mentioned that every JavaScript or TypeScript file in the `pages` directory is compiled into a route. However, there are some files that are ignored by the router. These files are:
* Files that start with an underscore (`_`)
* Files that end with `.d.ts`
These are seen as type declarations or setup files, and will be ignored by the router. Now moving on to files that will actually be loaded, let's look at index routes
## **Index Routes**
Hana automatically maps index files (index.jsx/index.tsx) to the directory name. For example, if you create a file called `index.tsx` in the `pages/home` directory, it will create a route for `/home`. An `index.jsx` file in the `pages` directory will create a route for `/`.
* `pages/index.tsx` -> `/`
* `pages/home/index.jsx` -> `/home`
## **Nested Routes**
The router allows you to nest your components within folders to create nested routes. For example, you can add a new `/dashboard/settings` route by nesting a `settings.tsx` file inside a `dashboard` folder or by an `index.tsx` file inside a `settings` folder inside a `dashboard` folder.
* `pages/dashboard/settings.tsx` -> `/dashboard/settings`
* `pages/dashboard/settings/index.tsx` -> `/dashboard/settings`
## Dynamic Routing
Dynamic routing is the idea of creating routes that aren't fixed. For example, leaf's [x.com](http://x.com) profile is x.com/leafphp, but yours is x.com/username. Since there's no real way for X to know what username you'd set, your profile link can't be hardcoded, and so we call that a dynamic route. Hana's router provides everything you'll need for dynamic routing right out of the box, and you can find the [full documentation here](/routing/dynamic)
## Navigating between pages
After you've added your routes, the next thing is creating a link between them, whether it's through a navbar, footer or redirects, you can do so easily:
```tsx theme={"theme":"ayu-dark"}
import { Link,useNavigate } from '@hanabira/router';
export default function Home() {
const navigate = useNavigate();
return (
About
);
}
```
You can find the full docs on [the navigation page](/routing/navigating)
## **Setup Files**
Setup files are files that start with an underscore (`_`). These files are used to set up different functionality for your app. For example, you can use a setup file to set up global styles or components that should be available to all routes.
### **\_app.tsx**
The `_app.tsx` file is used to set up global styles or components that should be available to all routes. It is also used to wrap all routes in a layout component. This file is heavily inspired by Next.js' `_app.tsx` file. The example below sets up Hana Store.
```tsx src/pages/_app.tsx theme={"theme":"ayu-dark"}
import { PersistedState, createStore } from '@hanabira/store';
import './index.css';
createStore({
state: {
count: 0,
},
reducers: {
increment(state) {
return {
count: state.count + 1,
};
},
},
plugins: [PersistedState],
});
const Application: React.FC = ({ children }) => {
return <>{children}>;
};
export default Application;
```
### **\_error & \_404**
Hana allows you to set up error handlers for both 500 and 404 errors. You can check out the [**error handling**](/routing/errors) section to learn more.
### **\_loading**
Hana allows you to set up a loading component that is shown when a route is loading. You can check out the [**loading component**](/routing/layouts) section to learn more.
# Layouts
Source: https://docs.hana.leafphp.dev/routing/layouts
Wrap a structure or state around your page
Layouts allow you create a structure that is applied to a set of routes, for instance you can have a dashboard layout that is applied to all your dashboard routes. Layouts allow you write components like your headers, footers and sidebars once and apply them wherever necessary
## **Creating a Layout**
Hana automatically detects your layout component by looking for a `_layout.tsx` file in the `pages` directory. The `_layout.tsx` file should export a React component that will be rendered while a page is being fetched.
```tsx src/pages/_layout.tsx theme={"theme":"ayu-dark"}
const Layout: React.FC = ({ children }) => {
return (
Header
{children}
);
};
export default Layout;
```
## **Scoped Layout Components**
Hana allows you to have multiple `_layout.tsx` files. For example, you can have a `_layout.tsx` file in the `pages/users` directory that will be used for all pages in the `/users` directory.
```
|- pages
|- index.tsx
|- _layout.tsx
|- users
|- _layout.tsx
```
Considering the directory structure above, the `_layout.tsx` file in the `pages/users` directory will be used for all pages in the `/users` directory. The `_layout.tsx` file in the `pages` directory will be used for all other pages.
## Loading Layouts
You can also create layouts that show up only a page is being loaded by adding a `_loading` file. This uses React's [**Suspense**](https://react.dev/reference/react/Suspense) API under the hood, so you can use it with any asynchronous data fetching library.
```tsx src/pages/_loading.tsx theme={"theme":"ayu-dark"}
const Loading: React.FC = () => {
return