This is a React Server Component, which allows you to fetch directly inside the component asynchronously. I'd suggest to use it as much as possible, as long as you don't need client interactions inside the component. useEffect fetches client side, meaning that your API is exposed to the client, which is solved with the server components. There you can use API keys and secret tokens directly from the env, without thinking about client exposure. Answer from HilariousHudgens on reddit.com
๐ŸŒ
DEV Community
dev.to โ€บ stlnick โ€บ useeffect-and-async-4da8
`useEffect()` and `async` - DEV Community
August 10, 2020 - One such thing that took a little digging for me is the combination of useEffect() - essentially the replacement for componentDidMount, componentDidUpdate, and componentWillUnmount - and async/await.
๐ŸŒ
Reddit
reddit.com โ€บ r/nextjs โ€บ async component with fetch vs useeffect with fetch?
r/nextjs on Reddit: Async component with fetch vs useEffect with fetch?
January 26, 2024 -

I just saw this in the docs:

async function getData() {
  const res = await fetch('https://api.example.com/...')
  // The return value is *not* serialized
  // You can return Date, Map, Set, etc.
 
  if (!res.ok) {
    // This will activate the closest `error.js` Error Boundary
    throw new Error('Failed to fetch data')
  }
 
  return res.json()
}
 
export default async function Page() {
  const data = await getData()
 
  return <main></main>
}

Up to now, any time i've had fetching i've done a useEffect (and then marked the component as 'use client'). I've always figured this reduces performance, but the site seems to work fine. But now i'm looking at this and wondering when i should be doing this type of thing instead?

Also with this example above, if i host this on vercel, what does it count towards usage-wise? Edge Functions? Edge Middleware? Serverless Function Execution?

Top answer
1 of 2
2
This is a React Server Component, which allows you to fetch directly inside the component asynchronously. I'd suggest to use it as much as possible, as long as you don't need client interactions inside the component. useEffect fetches client side, meaning that your API is exposed to the client, which is solved with the server components. There you can use API keys and secret tokens directly from the env, without thinking about client exposure.
2 of 2
2
In the above code, the ordering is server fetches data server renders component using that data server gives client rendered components with the standard useEffect pattern in nextjs the order is server renders component without data and gives to client client fetches data (usually from the server itself) client fills in component with data the primary benefit of RSCs is that the server, which is usually more powerful, basically does all the work. the client also only makes 1 request to the server instead of 2. the main con is that the component skeleton will load slower, because it has to render + fetch the data before returning to the client, instead of just rendering the component with a spinner. i've personally found that depending on the data flow and how often the data needs to be fetched, RSCs can be a simpler mental model. useEffect and client state management can get a bit messy for even simple things. > what does it count towards usage-wise this will just be a serverless function, edge functions you would have to explicitly specify and they're more for simple data fetching.
Discussions

reactjs - next.js13 fetching data with an async function and also use state? - Stack Overflow
i hope you are having a great day ! i got a question... i'm currently learning next.js 13 and so i thought doing a personal project with it would be a good idea . Currently i'm doing an e-commmerce... More on stackoverflow.com
๐ŸŒ stackoverflow.com
reactjs - How to implement useEffect in the server in Next.JS 14? - Stack Overflow
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. More on stackoverflow.com
๐ŸŒ stackoverflow.com
How to use async functions in useEffect (with examples)
Sure, it will work, just don't forget cleanup: useEffect(() => { let isCanceled = false; const fetchData = async () => { const data = await fetch(`https://yourapi.com?someParam=${param}`); const json = await response.json(); if (!isCanceled) { setData(json); } } fetchData(); return () => { isCanceled = true; }; }, [param]) Otherwise you may get race condition: say, dependency changes before response comes and useEffect triggers and sends second request. Once responses return in wrong order, you may get you UI rendering incorrect data. This point is not directly related to "how to use await inside of useEffect?" but I notice people missed this point really often when dealing with async operations in useEffect More on reddit.com
๐ŸŒ r/reactjs
36
47
August 14, 2021
Run async code in nextjs component without using UseEffect
In my nextjs app, I have a StrapiImage component that accepts an image object from my strapi backend api as a prop. It assigns the width, height and url + any aditional props (it's basically a shor... More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Medium
medium.com โ€บ @ojogbomichael โ€บ useeffect-in-nextjs-435a6d60cb8d
UseEffect in NextJS. Effect /ษชหˆfษ›kt - by Michael Ojogbo
January 26, 2024 - You can also use the useEffect hook to run async functions on clientside components. In NextJS, the useEffect hook is not designed to work directly with asynchronous functions, and you cannot mark a useEffect callback as async.
๐ŸŒ
Devtrium
devtrium.com โ€บ posts โ€บ async-functions-useeffect
How to use async functions in useEffect (with examples) - Devtrium
August 14, 2021 - So how should you use the result of asynchronous code inside a useEffect? Inside the fetch data function!
๐ŸŒ
Next.js
nextjs.org โ€บ docs โ€บ messages โ€บ no-async-client-component
No async Client Component | Next.js
'use client' import { useState, useEffect } from 'react' export function Posts() { const [posts, setPosts] = useState(null) useEffect(() => { async function fetchPosts() { const res = await fetch('https://api.vercel.app/blog') const data = await res.json() setPosts(data) } fetchPosts() }, []) if (!posts) return <div>Loading...</div> return ( <ul> {posts.map((post) => ( <li key={post.id}>{post.title}</li> ))} </ul> ) }
๐ŸŒ
Ultimate Courses
ultimatecourses.com โ€บ blog โ€บ using-async-await-inside-react-use-effect-hook
Using Async Await Inside React's useEffect() Hook - Ultimate Courses
Simply put, we should use an async function inside the useEffect hook. There are two patterns you could use, an immediately-invoked function expression (my preferred approach), or a named function that you invoke.
Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ how to use async functions in useeffect (with examples)
r/reactjs on Reddit: How to use async functions in useEffect (with examples)
August 14, 2021 - You can't use an async function directly in useEffect because it returns a promise, but the return value of useEffect is supposed to be a bare callback function for cleaning up side effect.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 75496210 โ€บ run-async-code-in-nextjs-component-without-using-useeffect
Run async code in nextjs component without using UseEffect
There's a problem with this though, to generate the image, I need to use an await statement. In getStaticProps, this wouldn't be a problem as I could just make the function async, but I'm doing this inside a component and components must regular non-async functions. The 'obvious' solution would be to use the useEffect hook like so:
๐ŸŒ
React
react.dev โ€บ reference โ€บ react โ€บ useEffect
useEffect โ€“ React
You can also rewrite using the async / await syntax, but you still need to provide a cleanup function: ... import { useState, useEffect } from 'react'; import { fetchBio } from './api.js'; export default function Page() { const [person, setPerson] = useState('Alice'); const [bio, setBio] = useState(null); useEffect(() => { async function startFetching() { setBio(null); const result = await fetchBio(person); if (!ignore) { setBio(result); } } let ignore = false; startFetching(); return () => { ignore = true; } }, [person]); return ( <> <select value={person} onChange={e => { setPerson(e.target.value); }}> <option value="Alice">Alice</option> <option value="Bob">Bob</option> <option value="Taylor">Taylor</option> </select> <hr /> <p><i>{bio ??
๐ŸŒ
DhiWise
dhiwise.com โ€บ post โ€บ nextjs-useeffect-guide-for-managing-side-effects
Next.js useEffect for Effective Side Effect Management
June 7, 2024 - Error handling in useEffect should be done using try-catch blocks within the asynchronous function.
๐ŸŒ
Next.js
nextjs.org โ€บ docs โ€บ pages โ€บ building-your-application โ€บ data-fetching โ€บ client-side
Data Fetching: Client-side Fetching | Next.js
6 days ago - import { useState, useEffect } from 'react' function Profile() { const [data, setData] = useState(null) const [isLoading, setLoading] = useState(true) useEffect(() => { fetch('/api/profile-data') .then((res) => res.json()) .then((data) => { setData(data) setLoading(false) }) }, []) if (isLoading) return <p>Loading...</p> if (!data) return <p>No profile data</p> return ( <div> <h1>{data.name}</h1> <p>{data.bio}</p> </div> ) }
๐ŸŒ
Code with Mosh
forum.codewithmosh.com โ€บ next.js
Why use useEffect() hook - Next.js
April 30, 2024 - Hi all, I am following along in the NextJS course building the Issue Tracker. I am on the section called "Populate the Assignee dropdown. In the code he is using the useEffect() hook. He does not explain why, just says go back to my React course. So far, this is the only code that uses that ...
๐ŸŒ
Next.js
nextjs.org โ€บ docs โ€บ pages โ€บ building-your-application โ€บ rendering โ€บ client-side-rendering
Rendering: Client-side Rendering (CSR) | Next.js
6 days ago - import React, { useState, useEffect } from 'react' export function Page() { const [data, setData] = useState(null) useEffect(() => { const fetchData = async () => { const response = await fetch('https://api.example.com/data') if (!response.ok) { throw new Error(`HTTP error!
๐ŸŒ
Jason Watmore's Blog
jasonwatmore.com โ€บ next-js-13-fix-for-client-component-use-client-hangs-when-fetching-data-in-useeffect-hook
Next.js 13 - Fix for client component ('use client') hangs when fetching data in useEffect hook | Jason Watmore's Blog
June 29, 2023 - Through some trial and error I ... throwing my laptop out the window! lol... After a lot of digging around online I found the answer: Client components cannot be marked async....