Router

useRouter

Router context hook for accessing navigation state and methods.

useRouter()

The useRouter hook provides access to the router's internal state, including current path, parameters, and navigation methods.

Hook Signature

import {  } from 'manicjs';

export default function () {
  const  = ();
  // ...
}

Return Value

Prop

Type

Examples

Basic Usage

import React from 'react';
import {  } from 'manicjs';

export default function () {
  const { ,  } = ();
  
  return (
    <>
      <>Current path: {}</>
      <>User ID: {.}</>
    </>
  );
}

With Dynamic Path

import React from 'react';
import {  } from 'manicjs';

export function ({  }: { : <{ : string; : string }> }) {
  return (
    <>
      {.( => (
        < ={.}>
          < ={`/posts/${.}`}>{.}</>
        </>
      ))}
    </>
  );
}

Multiple Route Parameters

import React from 'react';
import {  } from 'manicjs';

// File: app/routes/users/[userId]/posts/[postId].tsx
export default function () {
  const {  } = ();
  // { userId: "123", postId: "456" }
  
  return (
    <>
      User {.}'s Post {.}
    </>
  );
}

Programmatic Navigation

import React from 'react';
import {  } from 'react';
import {  } from 'manicjs';

export function () {
  const {  } = ();
  const [, ] = ('');
  const [, ] = ('');
  
  const  = async () => {
    const  = await ('/api/login', {
      : 'POST',
      : .({ ,  }),
    });
    
    if (.) {
      ('/dashboard');
    }
  };
  
  return < ={}>Login</>;
}

Route Guards

import React from 'react';
import { ,  } from 'react';
import {  } from 'manicjs';

export default function () {
  const { ,  } = ();
  const [, ] = <any>(null);
  
  (() => {
    // Fetch user data
    ('/api/me').( => .()).();
  }, []);
  
  (() => {
    // Redirect if not admin
    if ( && !.isAdmin) {
      ('/unauthorized', { : true });
    }
  }, []);

  if (!?.isAdmin) return null;
  
  return <>Admin Panel</>;
}

Type Definitions

interface NavigateOptions {
  replace?: boolean;
}

interface RouterContextValue {
  path: string;
  params: Record<string, string>;
  navigate: (to: string, options?: NavigateOptions) => void;
}

declare function useRouter(): RouterContextValue;

Notes

  • Must be called inside a component rendered by the router
  • Returns null or throws if called outside router context
  • params is empty object for static routes without dynamic segments

See Also

On this page