HomeDocsGithub
Docs/Reference/useRouter

useRouter

The useRouter hook provides client components access to Twofold's router. This hook is used to navigate between pages, preform refreshes, and access the current route.

Usage

To use the useRouter hook:

// src/pages/client-component.tsx

"use client";

import { useRouter } from "@twofold/framework/use-router";

export default function ClientComponent() {
  let router = useRouter();

  return <p>The current path is {router.path}</p>;
}

The useRouter hook can only be used in client components since it is a reactive hook that updates and re-renders as users navigate between pages.

Programmatic navigation can be achieved by calling the navigate or replace functions from useRouter:

// src/pages/client-component.tsx

"use client";

import { useRouter } from "@twofold/framework/use-router";
import { useEffect } from "react";

export default function ClientComponent() {
  let { navigate } = useRouter();

  useEffect(() => {
    let id = setTimeout(() => {
      navigate("/new-page");
    }, 1_000 * 60);

    return () => {
      clearTimeout(id);
    };
  }, [navigate]);

  return <p>You can only read this page for 1 minute, then we kick you out!</p>;
}

In the example above, the user will automatically navigate to /new-page after 1 minute.

The replace function from useRouter can be used instead of navigate. The only difference is that unlike navigate, it will replace the current page in the history stack instead of pushing a new entry.

Refreshing Pages & Layouts

The refresh function from useRouter can be used to refresh the current page and its layouts:

// src/pages/client-component.tsx

"use client";

import { useRouter } from "@twofold/framework/use-router";
import { useEffect } from "react";

export default function ClientComponent() {
  let { refresh } = useRouter();

  useEffect(() => {
    let id = setInterval(() => {
      refresh();
    }, 1_000 * 60);

    return () => {
      clearTimeout(id);
    };
  }, [refresh]);

  return <p>Data will be updated every minute!</p>;
}

This component will refresh the data fetched from the page and layouts once a minute. The refresh function will only update the data from server components, it leaves data and state associated with client components intact.

Return values

The functions and values returned by useRouter:

// src/pages/client-component.tsx

"use client";

import { useRouter } from "@twofold/framework/use-router";

function ClientComponent() {
  let { path, navigate, replace, refresh } = useRouter();

  // ...
}

The useRouter hook returns an object with the following properties:

PropertyTypeDescription
pathstringThe current path of the router.
navigate(path: string) => voidA function to navigate to a new page.
replace(path: string) => voidA function to replace the current page in the history stack.
refresh() => voidA function to refresh the current page and its layouts.