Next.js Discord

Discord Forum

hooks inside dynamic routes

Answered
Sloth bear posted this in #help-forum
Open in Discord
Sloth bearOP
how do i use hooks with dynamic routes if the page is async? linter is complaining about hooks being called inside async function

10 Replies

@Sloth bear how do i use hooks with dynamic routes if the page is async? linter is complaining about hooks being called inside async function
You need to be inside a Client boundary in order to use Hooks (most of them)
For that, your file needs to be annotated with "use client" at the very top, this will turn your components declared inside and all the component imports turn into Client components
"use client";

import { useState } from "react";

export function MyClientComponent() {
    const [state, setState] = useState( ... );
    // ...
}
@luis_llanes You need to be inside a *Client boundary* in order to use Hooks (most of them) For that, your file needs to be annotated with "use client" at the very top, this will turn your components declared inside and all the component imports turn into Client components
Sloth bearOP
how do i access the params with use client?
interface BoxProps {
  params: Promise<{ id: string }>;
}

export default async function Foo({ params }: BoxProps) {
  // ...
}
useParams hook
Next.js provides that hook
Sloth bearOP
ohh thankss i don't know that, i tried searching around the documentation and i haven't seen it
Answer
'use client'
 
import { useParams } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const params = useParams<MyParamsType>() 
  return '...'
}
Sloth bearOP
thank you
Of course