# 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 image.png ## 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}
Footer
); }; 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
Loading...
; }; export default Loading; ``` And just like with `_layout` files, your loading layout files can also be scoped to particular folders, and you can have as many as you need in your application ``` |- pages |- index.tsx |- _loading.tsx |- users |- _loading.tsx ``` # Navigating Source: https://docs.hana.leafphp.dev/routing/navigating Move between pages in your application Hana's router is built on top of react router, so uses similar methods for navigating your pages: * `` * `useNavigate` ## Using Link `` is a built-in component that renders an HTML `` tag. It allows users navigate to another page by clicking or tapping on it. It is the primary way to navigate between routes in Hana. ```tsx theme={"theme":"ayu-dark"} import { Link } from '@hanabira/router'; export default function Home() { return (
About
); } ``` ### Link Props * `to` - The path to navigate to. This can be a string or an object. * `replace` - If `true`, clicking the link will replace the current entry in the history stack instead of adding a new one. * `state` - The `state` property can be used to set a stateful value for the new location which is stored inside history state. This value can subsequently be accessed via `useLocation()` ```tsx theme={"theme":"ayu-dark"} ... ``` On the `/next-path` page, you can access the state value like this: ```tsx theme={"theme":"ayu-dark"} import { useLocation } from '@hanabira/router'; export default function NextPath() { const { state } = useLocation(); return
{state.something}
; } ``` For more information on the `` component, check out the base [**React Router documentation**](https://reactrouter.com/en/main/components/link#link). ## Using navigation hooks The `useNavigate` hook is used to navigate to a new location. It is the programmatic way to navigate between routes. ```tsx theme={"theme":"ayu-dark"} import { useNavigate } from '@hanabira/router'; export default function Home() { const navigate = useNavigate(); return (
); } ``` ### Hook options The `navigate` function accepts a route string as its first argument and an options object as its second argument. ```tsx theme={"theme":"ayu-dark"} const navigate = useNavigate(); navigate('/about', { replace: true }); ``` * `replace` - If `true`, the current entry in the history stack will be replaced instead of adding a new one. * `state` - The `state` property can be used to set a stateful value for the new location which is stored inside history state. This value can subsequently be accessed via `useLocation()`. You can find more information on the `useNavigate` hook in the base [**React Router documentation**](https://reactrouter.com/en/main/hooks/use-navigate) ## Search Params The `useSearchParams` hook is used to access the query string parameters of the current location. It returns an array containing an object with the query string parameters and a function to update the query string parameters ```tsx theme={"theme":"ayu-dark"} import { useSearchParams } from '@hanabira/router'; export default function Home() { const [searchParams, setSearchParams] = useSearchParams(); return (
Search Params: {JSON.stringify(searchParams)}
); } ``` # State Management Source: https://docs.hana.leafphp.dev/state/index Global state management without all the pain React provides the context API for handling state globally in your application. While it's not bad in its own right, it requires a ton of boilerplate and maintaining a different context provider for each feature subset quickly gets out of hand in slightly bigger applications Hana Store solves this issue by providing a one-line way to interact with the context API so you don't have to create all the boilerplate required to store and get items in your apps. Hana Store is automatically added to projects generated using `create-hana-app`, but if you already have a React or React Native project, you can install and use it instantly **Install from npm** ```bash theme={"theme":"ayu-dark"} npm install @hanabira/store ``` ## Using your store Hana store uses a very similar syntax to React's built-in `useState()` which allows you to read & write from the same hook. The `useStore()` hook takes in the name of the item in the store you want to use, and returns a setter/getter for it. ```tsx theme={"theme":"ayu-dark"} import { useStore } from '@hanabira/store'; ... const [item, setItem] = useStore('item'); return (

Value: {item}

); ``` Although Hana Store requires no setup, it allows you to customize it with some pretty cool updates ## Store Initialization Hana allows you to initialize your store with your own configuration which allows you to do things like setting an initial state, use state modules, sync to an external storage like localStorage or Async Storage, and so much more ```tsx src/pages/_app.tsx theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; const store = createStore({ state: { item: 'Initial value', }, reducers: { setItem: (state, payload) => ({ ...state, item: payload }), }, compareState: true, plugins: [], }); ... // your app here ``` The `state` key allows you to initialize your store with default values which will be returned on the initial load instead of `null` . This is especially useful when using TypeScript so you can prevent redundant `null` checks and avoid using `?.` You should only use `createStore()`once in your application, and in a root component like the `_app` or similar ## Syncing to external storage It's very common to persist your state to an external or on-device storage, which allows you to maintain the application's state even when the application is closed or device is restarted. This usually require's annoying boilerplate or using an effect to watch states which run quite ineffeciently. Hana's solution to this problem is a built-in store plugin that automatically syncs your global state to the browser's localStorage or any other storage of your choice if specified ```tsx theme={"theme":"ayu-dark"} import { PersistedState, createStore } from '@hanabira/store'; createStore({ plugins: [PersistedState], }); ``` You can pass some extra config to the `PersistedState` ```tsx theme={"theme":"ayu-dark"} import { PersistedState, createStore } from '@hanabira/store'; import AsyncStorage from '@react-native-async-storage/async-storage'; createStore({ plugins: [ new PersistedState({ storage: AsyncStorage, env: 'react-native', }), ], }); ``` * The `env` property is used to tell the plugin that it is running in a React Native environment. This is important because React Native does not have a `window` object. If you do not pass this property, the plugin will assume that it is running in a browser environment. * The `storage` property is used to tell the plugin which storage medium to use. This property can be any object that implements the `Storage` interface. This includes `localStorage`, `sessionStorage`, and `AsyncStorage` from React Native. * It also supports a `key` property which is used to specify the key to use when saving the state. This defaults to `hana-store`. ```tsx theme={"theme":"ayu-dark"} createStore({ plugins: [ new PersistedState({ key: 'my-app-store', }), ], }); ``` * There is also an `exclude` property is an array of keys that should not be persisted. This is useful for excluding sensitive data like passwords and tokens from being persisted. If a value is excluded, it will not be persisted, but it will still be available in the state object. ```tsx theme={"theme":"ayu-dark"} createStore({ plugins: [ new PersistedState({ exclude: ['password', 'token'], }), ], }); ``` * The `include` property is an array of keys that should be persisted. This is useful for persisting only certain values in the state object. If the `include` property is set, the `exclude` property will be ignored and only the values in the `include` property will be persisted. ```tsx theme={"theme":"ayu-dark"} createStore({ plugins: [ new PersistedState({ include: ['user'], }), ], }); ``` # Store Modules Source: https://docs.hana.leafphp.dev/state/modules Single store vs atoms, which wins? Two main paradigms exist when it comes to global state management, not just in React, but other frameworks too. Some prefer atomic states which are small, lightweight stores holding the store for just a subset of features, the other school prefers a giant store holding everything in your application. Hana uses the latter, as it enables a no-boilerplate, no-config setup: ```tsx theme={"theme":"ayu-dark"} import { useStore } from '@hanabira/store'; const Component = () => { const [item, setItem] = useStore('item'); return (

{item}

); }; ``` And all data is imeedietly synced to the single store on set. While this is great in terms of simplicity and ease-of-use, its easy to quickly make a mess of the `createStore()` function, especially when you start taking advantage of reducers and default states for lots of different features. Modules allow you mimick the atomic state model, where you can break your state into "modules" by feature ## Creating a store module A module contains the initial state & reducers of a feature-set, and is solely for organization reasons. It does not change the way Hana Store works in any way, but makes your code more organized and easier to create a mental model about ```typescript theme={"theme":"ayu-dark"} import { LOCALE_STORAGE_AUTH_KEY, LOCALE_STORAGE_REFRESH_TOKEN, } from '@/utils/constants'; import type { Module } from '@hanabira/store'; const AuthState: Module = { namespace: 'auth', state: { user: null, isAuth: false, [LOCALE_STORAGE_AUTH_KEY]: null, [LOCALE_STORAGE_REFRESH_TOKEN]: null, }, reducers: { logout: (state) => ({ ...state, user: null, isAuth: false }), login: (state, payload) => ({ ...state, isAuth: true, user: payload.user, [LOCALE_STORAGE_AUTH_KEY]: payload.token, [LOCALE_STORAGE_REFRESH_TOKEN]: payload.refreshToken, }), }, }; export default AuthState; ``` This `AuthState` module contains: * the initial state for the auth state of the application * `login` and `logout` reducers which just update the state * A namespace `auth` for the state and reducers in this module ## Registering a module You can add all your created modules in the `createStore()` function like this: ```tsx theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; import AuthState from '@/store/auth'; const store = createStore({ ..., // Other config modules: [AuthState], }); ``` This will automatically load the state & reducers to the global state so you can use them just as before ## Module Namespaces In bigger applications, it gets difficult keeping track of the state keys, and you may end up overwriting some of them by using the same names. To fix this, Hana allows you to namespace your modules, and this will automatically append the namespace to the state/reducer key ```typescript theme={"theme":"ayu-dark"} const AuthState: Module = { namespace: 'auth', state: { user: null, }, reducers: { logout: (state) => ({ ...state, user: null }), login: (state, payload) => ({ ...state, user: payload.user, }), }, }; ``` Once this is registered, you can use the module values like this: ```tsx theme={"theme":"ayu-dark"} import { useStore } from '@hanabira/store'; const Component = () => { const [user, setUser] = useStore('auth.user'); return (

{user?.name || 'Unknown'}

); }; ``` This is the same syntax for using state values, except we appended the module namespace to the state key. It works the same way for reducers: ```tsx theme={"theme":"ayu-dark"} import { useReducer } from '@hanabira/store'; const Component = () => { const logout = useReducer('auth.logout'); return (
); }; ``` # Plugins Source: https://docs.hana.leafphp.dev/state/plugins Sometimes, you may need access to some functionality that is not provided by Hana. In this case, you can use a plugin. Plugins are functions that are called at specific points in the Store lifecycle. They can be used to add additional functionality to the Store. ## **Creating a Plugin**[**#**](https://tourmaline-bonbon-28a2af.netlify.app/store/plugins.html#creating-a-plugin) A plugin is basically a class that implements the `Plugin` interface. This interface contains the following methods: * `onReady()`: Called when the Store is ready. * `onSave()`: Called when a value is saved or updated in the Store. * `onRead()`: Called when a value is read from the Store. * `onReducerInvoke()`: Called when a reducer is called. * `onReset()`: Called when the Store is reset. Example: ```typescript theme={"theme":"ayu-dark"} class MyPlugin implements Plugin { onReady(state) { console.log('Store is ready'); } onSave(state) { console.log('The updated state is ', JSON.stringify(value)); } onRead(state) { // } onReducerInvoke(state) { // } onReset(state) { // } } ``` ## **Using a Plugin**[**#**](https://tourmaline-bonbon-28a2af.netlify.app/store/plugins.html#using-a-plugin) To use a plugin, you need to pass it to the `createStore()` function as part of the configuration object. This object takes in a `plugins` property which is an array of plugins to use with the Store. ```typescript theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; const store = createStore({ plugins: [MyPlugin], }); ``` Depending on the plugin, you may need to pass some options to it. For example, the Persisted State plugin can take options to exclude certain values from being persisted. For those cases, you may want to pass an initialized instance of the plugin to the `createStore()` function. ```typescript theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; const store = createStore({ plugins: [new MyPlugin({ ...options })], }); ``` # Reducers Source: https://docs.hana.leafphp.dev/state/reducers Abstract multiple state actions into a single store function Hana allows you easily set and get your global state using the `useStore()` hook, and while this is super easy, it quickly gets annoying if you have to work with multiple state values, especially if they are all working towards the same feature. Reducers allow you to abstract all that into a single function which can be called from anywhere in your app, using the `useReducer()` hook. ## Defining a reducer At the core, a Hana reducer is just a function that accepts two arguments: * The current global state * A payload passed in from when the function is called ```tsx theme={"theme":"ayu-dark"} const setFromPayload = (state, payload) => { // Perform some operations return { ...state, ...payload, }; }; ``` This function returns a new application state, while allowing you to perform additional actions. ## Registering a reducer Hana reducers are registered globally so they can be used anywhere in your app without carrying over the entire function as done in other reducer implementations. In Hana, all you need is the reducer name. You can register the reducer globally using: * The `createStore()` function right on init * `useReducer()` but this can cause problems if not done right ### Using `createStore()` `createStore()` is OPTIONALLY used to initialize your global store with default options like the initial state, reducers, modules and other items. To add reducers, you can either [use a module](/state/modules) or pass the reducer directly like this: ```tsx theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; createStore({ ..., // Other config reducers: { setItems: (state, payload) => { // perform some operation const items = state.items.reverse(); return { items: [ ...items, ...payload ], }; }, }, }); ``` The example above registers a reducer called `setItems` that reverses the order of the items in the state object and adds the payload to the end of the array. This reducer can be used in any component using the `useReducer()` hook, but we will get to that later. ### \*\*Using \*\*`useReducer()` This hook takes in the reducer function you want to register, and uses the name of the function as the name of the reducer. This means that the name of the reducer function must be the same as the name of the reducer you want to register. We recommend using `createStore()` to register all your reducers instead of `useReducer()` because this method heavily depends on execution order. If the user calls a component that requires the reducer before it is registered, you could break your application. You should use this method to register your reducers ONLY if you can guarantee the correct execution order ```tsx theme={"theme":"ayu-dark"} import { useReducer } from '@hanabira/store'; const setItems = (state, payload) => {...}; const Component = () => { const addToList = useReducer(setItems); return (
); }; ``` In this case, the reducer is passed directly to `useReducer()` . It will take the function name which is `setItems()` in this case, and register it globally so you can use it in other components without needing to export the function first: ```tsx theme={"theme":"ayu-dark"} import { useReducer } from '@hanabira/store'; const Component = () => { const setItems = useReducer('setItems'); // items is an array of items the user wants to add to the list const addItemsToList = (items) => { setItems(items); }; ... }; ``` Remember that this will only work if the component with the initial `useReducer()` is called first ## Using a reducer After registering your reducer globally, the easy part is using your reducer to do all the cool magical state updates with just one function. Let's look at an example where some data is collected from an API response and synced to state: ```tsx theme={"theme":"ayu-dark"} const [, setUser] = useStore('user'); const [, setWallets] = useStore('wallets'); const [, setRecentContacts] = useStore('recentContacts'); ... const setDataFromResponse = async () => { const data = await getResponse(); setUser(data.user); setWallets(data.wallets); setRecentContacts(data.recentContacts); } ``` While this isn't too bad, our `setItems()` from will allow us to do this same thing in a much more elegant way: ```tsx theme={"theme":"ayu-dark"} const writeToStore = useReducer('setItems'); ... const setDataFromResponse = async () => { const data = await getResponse(); writeToStore({ user: data.user, wallets: data.wallets, recentContacts: data.recentContacts, }); } ``` While this is a super simple example and will probably not happen much in production, the idea is the same. Reducers allow you to define some actions that return a new state and are usually used for complex flows. ## Reducers with no values Most implementations of reducers force you to pass a payload into your reducer function, but that's totally optional with Hana. This allows you to define self-contained reducers that perform and internal action and update the state, for example, a logout action: ```tsx theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; createStore({ reducers: { logout: (state) => ({ ...state, token: null, refreshToken: null, user: null, anythingElseToUnset: null, }), }, }); ``` And then use it like this: ```tsx theme={"theme":"ayu-dark"} import { useReducer } from '@hanabira/store'; const LogoutButton = () => { const logout = useReducer('logout'); return ; }; ``` ## Reducers with async actions Hana reducers aren't just a handy way of setting your state values, you can also use them to perform async actions like fetching values from an API: ```tsx theme={"theme":"ayu-dark"} import { createStore } from '@hanabira/store'; createStore({ reducers: { addWallet: async (state, payload) => { const response = await linkNewWallet(payload); return { ...state, balance: response.data.balance, wallets: [ ...state.wallets, response.data.wallet, ], }; }, }, }); ``` And then you can use this `addWallet()` reducer to add a new wallet and update the user's balance in one elegant line: ```tsx theme={"theme":"ayu-dark"} import { useReducer } from '@hanabira/store'; const Component = () => { const addWallet = useReducer('addWallet'); const addToList = async () => { await addWallet({...}); }; ... }; ``` ## Skip re-rendering UI Sometimes, you may need to use a reducer in a component that does not actually re-render the UI after the reducer is called. In this case, you can use the `useStaticReducer()` hook. It works exactly like the `useReducer()` hook, but it does not cause the component to re-render when the reducer is called. ```tsx theme={"theme":"ayu-dark"} import { useStaticReducer } from '@hanabira/store'; const Component = () => { const setItems = useStaticReducer('setItems'); const addToList = (items) => { setItems(items); }; ... }; ```