Next.js Discord

Discord Forum

What is best way to refactor code client component to server component?

Answered
Giant panda posted this in #help-forum
Open in Discord
Giant pandaOP
I learned fetch data can be async when I code a page. Also I realize this called SSR mechanism do.
Then I coded a page, I have some concern about server action and how we refactor code.
When I coded some page, I used lots of use client component and it included many functions about react.

'use client';
// Assume that useQuery hook is react-query from tanstack
export default function Home() {
  const data = useQuery(...);
  const [example, setExample] = useState(); // react hook

  return (
    <div>
      {data.map((d, k) => (...)}
      {example && <div> ... </div>}
    </div>
  )
}


This code show a common code when I code a page.
I think this code is not a SSR so I refactor this code.

async function getData() {
  const res = useQuery();

  return res;
}
export default async function Home() {
  const data = await getData();

  return (
  <div>
    {data.map((d, k) => (...)}
    <Example data={data} />
  </div>
  )
}


Refactored code doesn't have a state hook. Because react-hook can only use a client component
Is this the right way refactoring code?
Answered by aardani
you put one in server for prefetching initial data
then put another one in useQuery to update data at runtime
View full answer

7 Replies

This code show a common code when I code a page.
First code can be SSR if you provide initial value in useQuery or provide initial state in useState
I think this code is not a SSR so I refactor this code.
Second code doesn't work because useQuery needs to only be used in the client component
So what about fetch. Is this a right way refactor code?
yep
you put one in server for prefetching initial data
then put another one in useQuery to update data at runtime
Answer
@aardani you put one in server for prefetching initial data then put another one in `useQuery` to update data at runtime
Giant pandaOP
Thank you. So split a useState hook is right way.