Can I use the UseEffect hook inside getStaticProps?
Asked Answered
P

2

8

I have a doubt.. can I use a useEffect inside getStaticProps?

I'm trying to run a function inside getStaticProps... it works.. but I don't know if it is the recommended thing to do.

  useEffect(() => {
    remarkBody()
  }, [body, blogPostCollection])

If not ... what is the best way to run it?

Pericline answered 1/3, 2021 at 23:18 Comment(0)
C
6

useEffect is used to execute code when component is mounted on client side, and when specific variables change.

getStaticProps is run only once on server side and at build time. You can put your code in the body of the function directly.

And anyway if you do it you will have this error:

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

Congregation answered 2/3, 2021 at 0:2 Comment(0)
H
4

in next.js data is fetched on the server. This is the key aspect of server side rendering. The main purpose of server-side rendering, is sending populated page, so browser crawlers can analyze the response page and this help better seo for your page. When client makes a request, before sending the response, next.js runs getStaticProps or getServerSideProps.

However useEffect runs on the client-side. The purpose of useEffect, to get data before components mount, so you can use that data inside the component.

Howe answered 2/3, 2021 at 1:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.