简体   繁体   中英

Can I use the UseEffect hook inside getStaticProps?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM