You're probably asking this because you want to use the default SSR in NextJS and it doesn't work with useEffect
code.
Think of useEffect
as a hacky way of awaiting for async functions. NextJS SSR components can be async, so, there's no reason to use useEffect
. Some example
Client component
This code would error because Home
is not async
export function Home() {
const foo = await someAsyncFunction();
return <h1>{foo}</h1>
}
Then you'd fix it with
export function Home() {
const [foo, setFoo] = useState<string>("");
const fetchFoo = async () => {
const foo = await someAsyncFunction();
setFoo(foo);
}
useEffect(() => {fetchFoo});
return <h1>{foo}</h1>
}
SSR component
In server rendered components, you don't need all the hacky stuff. Just make the component async.
export async function Home() {
const foo = await someAsyncFunction();
return <h1>{foo}</h1>
}