{"id":2224,"date":"2022-01-25T17:43:08","date_gmt":"2022-01-25T17:43:08","guid":{"rendered":"https:\/\/lvboard.infostore.in.ua\/?p=2224"},"modified":"2022-01-25T17:43:08","modified_gmt":"2022-01-25T17:43:08","slug":"get-started-with-next-js-the-react-library-your-project-needs","status":"publish","type":"post","link":"https:\/\/lvboard.infostore.in.ua\/?p=2224","title":{"rendered":"Get Started with Next.js \u2013 The React Library Your Project Needs"},"content":{"rendered":"\n<p><strong>The goal of this tutorial is to get you started using Next.js as easily as possible.<\/strong><\/p>\n\n\n\n<p>This is not a complete guide on Next, but it will give you everything you need to understand:<\/p>\n\n\n\n<!--more-->\n\n\n\n<ul><li>What Next.js is (and why you should start using it for your React projects)<\/li><li>How to perform essential tasks using Next.js<\/li><li>Plus how Next.js will help you build overall better React applications, faster<\/li><\/ul>\n\n\n\n<p>Let&#8217;s dive in!<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>I&#8217;ve helped 100s of people go from total beginners to hired React developers. Want to do the same? Check out&nbsp;<a href=\"https:\/\/reactbootcamp.com\/\"><strong>The React Bootcamp<\/strong><\/a>.<\/p><\/blockquote>\n\n\n\n<h2 id=\"table-of-contents\">Table of Contents<\/h2>\n\n\n\n<ul><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#what-is-next-js\">What is Next.js?<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#what-features-next-js-gives-you\">What Features Next.js Gives You<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#what-features-next-js-doesn-t-have\">What Features Next.js Doesn&#8217;t Have<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#how-to-create-a-next-js-app\">How to Create a Next.js App<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#next-js-scripts\">Next.js Scripts<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#add-typescript-to-next-js\">Add TypeScript to Next.js<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#pages-and-routes\">Pages and Routes<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#links-and-navigation\">Links and Navigation<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#seo-in-next-js\">SEO in Next.js<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#api-routes\">API Routes<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#request-data-client-side\">Request Data Client-side<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#request-data-server-side\">Request Data Server-side<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#getserversideprops\">GetServerSideProps<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#getstaticprops\">GetStaticProps<\/a><\/li><li><a href=\"https:\/\/www.freecodecamp.org\/news\/nextjs-tutorial\/amp\/#where-to-learn-next-js\">Where to Learn Next.js<\/a><\/li><\/ul>\n\n\n\n<h2 id=\"what-is-next-js\">What is Next.js?<\/h2>\n\n\n\n<p>The ultimate tool for any React developer to learn and improve their own projects is, without a doubt,&nbsp;<strong>Next.js<\/strong>.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.freecodecamp.org\/news\/content\/images\/2022\/01\/Screen-Shot-2022-01-14-at-12.12.20-PM.png\" alt=\"Screen-Shot-2022-01-14-at-12.12.20-PM\"\/><figcaption>The NextJS.org Homepage<\/figcaption><\/figure>\n\n\n\n<p>Whether I&#8217;m building a static site with interactivity like a blog, or a highly dynamic, full-stack project like a social media app,&nbsp;<em>I almost always reach for Next<\/em>.<\/p>\n\n\n\n<p>The first reason for you to use Next is, as the banner headline states, because it&#8217;s a&nbsp;<strong>React framework<\/strong>.<\/p>\n\n\n\n<p>Think of it as a &#8220;batteries-included&#8221; way to build your React applications, which gives you the simplicity of tools like Create React App, combined with a suite of other super powerful features.<\/p>\n\n\n\n<p>Despite being a framework, Next.js keeps some of the React philosophy of being unopinionated. Next gives you features to improve your overall development experience but doesn&#8217;t constrain the amount of options you can choose from.<\/p>\n\n\n\n<p>In fact, given what Next makes possible for React apps, I would contend that it has really expanded the number of options available to you, if you need it.<\/p>\n\n\n\n<p>You can get a more complete sense of everything Next.js apps are capable of by checking 100s of example Next.js projects at&nbsp;<a href=\"https:\/\/nextjs.org\/examples\">nextjs.org\/examples<\/a>:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.freecodecamp.org\/news\/content\/images\/2022\/01\/Screen-Shot-2022-01-14-at-1.56.57-PM.png\" alt=\"Screen-Shot-2022-01-14-at-1.56.57-PM\"\/><figcaption>Next.js Examples<\/figcaption><\/figure>\n\n\n\n<p>There you can find examples on how to create the following Next (React) apps:<\/p>\n\n\n\n<ul><li>A blog using Markdown \/ MDX or WordPress<\/li><li>An e-commerce app using Shopify<\/li><li>A site using content management systems like Contentful or Sanity<\/li><li>A full-stack project with GraphQL and Authentication<\/li><\/ul>\n\n\n\n<p>And tons more! Be sure to check out the full list to spark your imagination.<\/p>\n\n\n\n<h2 id=\"what-features-next-js-gives-you\">What Features Next.js Gives You<\/h2>\n\n\n\n<p>Below is a shortlist of what Next gives your React projects.<\/p>\n\n\n\n<p>In short, it provides the functionality of an entire suite of packages within a single&nbsp;<code>next<\/code>&nbsp;dependency.<\/p>\n\n\n\n<p>Next.js gives you:<\/p>\n\n\n\n<ul><li>Page-based routing (create a page by putting components in \/pages)<\/li><li>A built-in router (no need to install React Router)<\/li><li>API routes (write backend code using Node.js in \/pages\/api)<\/li><li>Super fast builds for development \/ production (see saved changes instantly)<\/li><li>Image and font optimization<\/li><li>Built-in ESLint and TypeScript support<\/li><li>+ tons more (all outlined in the&nbsp;<a href=\"https:\/\/nextjs.org\/docs\/\">Next.js documentation<\/a>)<\/li><\/ul>\n\n\n\n<h2 id=\"what-features-next-js-doesn-t-have\">What Features Next.js Doesn&#8217;t Have<\/h2>\n\n\n\n<p>Additionally there are many essential things that Next.js does not provide out of the box.<\/p>\n\n\n\n<p>For example, there is no built-in way to do the following in Next:<\/p>\n\n\n\n<ul><li>Authentication (I recommend using the package Next-Auth)<\/li><li>Testing (I recommend using Playwright or Cypress for your E2E tests)<\/li><li>State management (I recommend Zustand or Redux Toolkit)<\/li><\/ul>\n\n\n\n<p><a href=\"https:\/\/nextjs.org\/docs\/authentication\">The documentation itself<\/a>&nbsp;covers these shortcomings, but it is important to note that while Next.js gives you a great deal&nbsp;<strong>it will not alone cover every app use-case<\/strong>.<\/p>\n\n\n\n<h2 id=\"next-js-speedrun-\">Next.js Speedrun ?<\/h2>\n\n\n\n<p>I&#8217;ll give you the highlights of Next.js to give you a sense of how the framework gives you great defaults that make you more productive.<\/p>\n\n\n\n<h2 id=\"how-to-create-a-next-js-app\">How to Create a Next.js App<\/h2>\n\n\n\n<p>If you have NPM installed, start any new Next project with the command:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npx create-next-app my-next-project<\/code><\/pre>\n\n\n\n<p><code>create-next-app<\/code>&nbsp;is a package like Create React App, but for Next.js projects.<\/p>\n\n\n\n<p>In short, it gives us a Next project with all its dependencies installed (which are&nbsp;<code>next<\/code>,&nbsp;<code>react<\/code>, and&nbsp;<code>react-dom<\/code>) plus some dummy pages and styles.<\/p>\n\n\n\n<h2 id=\"next-js-scripts\">Next.js Scripts<\/h2>\n\n\n\n<p>You currently find four main scripts listed in your&nbsp;<code>package.json<\/code>&nbsp;file:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\"scripts\": {\n  \"dev\": \"next dev\",\n  \"build\": \"next build\",\n  \"start\": \"next start\",\n  \"lint\": \"next lint\"\n}<\/code><\/pre>\n\n\n\n<ul><li><code>dev<\/code>&nbsp;\u2013 runs a development server on localhost:3000<\/li><li><code>build<\/code>&nbsp;\u2013 creates a built application ready for deployment<\/li><li><code>start<\/code>&nbsp;\u2013 starts your built Next application (must run&nbsp;<code>next build<\/code>&nbsp;first)<\/li><li><code>lint<\/code>&nbsp;\u2013 will &#8220;lint&#8221; your Next project using the dev dependency ESLint to warn you if your written code needs to be fixed<\/li><\/ul>\n\n\n\n<p>To run your Next project in development, make sure you are in your project folder (my-next-project) and run the dev script:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>npm run dev<\/code><\/pre>\n\n\n\n<p>After your project is up and running on localhost:3000, navigate there and you should see a default app:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.freecodecamp.org\/news\/content\/images\/2022\/01\/Screen-Shot-2022-01-14-at-2.41.23-PM.png\" alt=\"Screen-Shot-2022-01-14-at-2.41.23-PM\"\/><figcaption>Index page of Create-Next-App project<\/figcaption><\/figure>\n\n\n\n<h2 id=\"add-typescript-to-next-js\">Add TypeScript to Next.js<\/h2>\n\n\n\n<p>Want to add TypeScript? Couldn&#8217;t be easier:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code># run 'touch' to create an empty config file\n# Next will auto-populate it\n\ntouch tsconfig.json \n\n# then you'll be prompted to run the command:\nnpm install -D typescript @types\/react @types\/node\n\n# now you can use TypeScript everywhere \u2728<\/code><\/pre>\n\n\n\n<h2 id=\"pages-and-routes\">Pages and Routes<\/h2>\n\n\n\n<p>Want to add an About page to your app?<\/p>\n\n\n\n<p>Just drop your component in \/pages\/about.js (.tsx if you&#8217;re using TypeScript):<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ No React import needed up here! ?\n\nexport default function About() {\n  return &lt;div&gt;About&lt;\/div&gt;\n}<\/code><\/pre>\n\n\n\n<p>And it works!<\/p>\n\n\n\n<p>This is a great advantage because we no longer have to install a library like React Router that requires boilerplate such as a Router and Route component, among others.<\/p>\n\n\n\n<p>If you would like dynamic pages, which are in the same folder but have different slugs (such as blog posts), Next allows us to render the same page component by wrapping the filename in brackets.<\/p>\n\n\n\n<p>For example, to display blog posts according to a particular slug, we could drop a &#8220;blog&#8221; folder in pages with the filename: [slug].js:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import { useRouter } from 'next\/router'\n\n\/\/ if we navigate to localhost:3000\/blog\/123...\nexport default function BlogPost() {\n  const router = useRouter()\n  const { slug } = router.query\n\n  return &lt;p&gt;Post: {slug}&lt;\/p&gt; \/\/ ...you'll see \"Post: 123\"\n}<\/code><\/pre>\n\n\n\n<p>Next conveniently exposes a&nbsp;<code>useRouter<\/code>&nbsp;React hook to make accessing information about the app location or history very easy.<\/p>\n\n\n\n<p>In this example, it allows us to get the query parameters (the dynamic value) from&nbsp;<code>router.query<\/code>. The property name&nbsp;<code>slug<\/code>&nbsp;matches the dynamic name we gave our file:&nbsp;<code>[slug].js<\/code>.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Note: You can have multiple query parameters due to using nested folders with dynamic names. Such as \/blog\/[topic]\/[slug].js. From within [slug].js, we could access both the&nbsp;<code>topic<\/code>&nbsp;and&nbsp;<code>slug<\/code>&nbsp;query params.<\/p><\/blockquote>\n\n\n\n<h2 id=\"links-and-navigation\">Links and Navigation<\/h2>\n\n\n\n<p>Just as Next includes routes and routing, the framework also gives us a helpful&nbsp;<code>Link<\/code>&nbsp;component from&nbsp;<code>next\/link<\/code>.<\/p>\n\n\n\n<p>It may look a bit unusual if you are coming from React Router, because it requires placing a traditional anchor tag link as a child and passing the href as a prop.<\/p>\n\n\n\n<p>If we wanted to link to the home page (\/) and a blog route (i.e. \/blog\/123), we would include the following in \/pages\/about.js:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Link from \"next\/link\";\n\nexport default function About() {\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;About Me&lt;\/h1&gt;\n      \n      &lt;div&gt;\n        &lt;Link href=\"\/\"&gt;\n          &lt;a&gt;Home&lt;\/a&gt;\n        &lt;\/Link&gt;\n        &lt;Link href=\"\/blog\/123\"&gt;\n          &lt;a&gt;My Blog Post&lt;\/a&gt;\n        &lt;\/Link&gt;\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code><\/pre>\n\n\n\n<p><code>href<\/code>&nbsp;is the only required prop for the&nbsp;<code>Link<\/code>&nbsp;component and data can be passed to it as an object as well:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Link from \"next\/link\";\n\nexport default function About() {\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;About Me&lt;\/h1&gt;\n\n      &lt;div&gt;\n        &lt;Link href={{ pathname: \"\/about\" }}&gt;\n          &lt;a&gt;Home&lt;\/a&gt;\n        &lt;\/Link&gt;\n        &lt;Link\n          href={{\n            pathname: \"\/blog\/&#91;slug]\",\n            query: { slug: \"123\" },\n          }}\n        &gt;\n          &lt;a&gt;My Blog Post&lt;\/a&gt;\n        &lt;\/Link&gt;\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}\n<\/code><\/pre>\n\n\n\n<p>Route changes can also be done using the&nbsp;<code>useRouter<\/code>&nbsp;hook, primarily using the&nbsp;<code>.push()<\/code>&nbsp;method to push to a different route programmatically.<\/p>\n\n\n\n<p>Here is a dummy example of a login page where a user provides their email to login and is pushed to the &#8216;\/verify-email&#8217; route afterwards.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export default function Login() {\n  const router = useRouter()\n    \n  function onSubmit(event) {\n    event.preventDefault();\n    const email = event.target.elements.email.value;  \n    await sendLoginEmail(email);    \n    \/\/ push user to \/verify-email page\n    router.push('\/verify-email');\n  }\n    \n  return (\n    &lt;div&gt;\n      &lt;h1&gt;Log in here&lt;\/h1&gt;\n\n      &lt;form onSubmit={onSubmit}&gt;\n        &lt;input name=\"email\" placeholder=\"Your email address\" \/&gt;\n        &lt;button type=\"submit\"&gt;Submit&lt;\/button&gt;\n      &lt;\/form&gt;\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<h2 id=\"seo-in-next-js\">SEO in Next.js<\/h2>\n\n\n\n<p>Pages in web applications not only need data within the HTML body, but meta (head) tags as well.<\/p>\n\n\n\n<p>In a Create React Application, this would require installing an external dependency called React Helmet.<\/p>\n\n\n\n<p>In Next, we can use the&nbsp;<code>Head<\/code>&nbsp;component from&nbsp;<code>next\/head<\/code>&nbsp;to conveniently add meta data to our webpages to be shown in search results and embeds:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Link from \"next\/link\";\nimport Head from \"next\/head\";\n\nexport default function About() {\n  return (\n    &lt;div&gt;\n      &lt;Head&gt;\n      \t&lt;title&gt;About | My Cool Site&lt;\/title&gt;\n        &lt;meta name=\"description\" content=\"You really need to read this website because it's made with Next.js\" \/&gt;\n      &lt;\/Head&gt;\n      \n      &lt;h1&gt;About Me&lt;\/h1&gt;\n      &lt;div&gt;\n        &lt;Link href=\"\/\"&gt;\n          &lt;a&gt;Home&lt;\/a&gt;\n        &lt;\/Link&gt;\n        &lt;Link href=\"\/blog\/123\"&gt;\n          &lt;a&gt;My Blog Post&lt;\/a&gt;\n        &lt;\/Link&gt;\n      &lt;\/div&gt;\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Note: The Head component should be included within any page component, usually right within the opening tag. You can create a reusable Head component that accepts dynamic values via props.<\/p><\/blockquote>\n\n\n\n<h2 id=\"api-routes\">API Routes<\/h2>\n\n\n\n<p>Need a backend \/ API for your project? No problem.<\/p>\n\n\n\n<p>One of the game-changers about Next is how is provides an all-in-one solution for creating full-stack React apps by giving you the ability to write server code using a feature called&nbsp;<strong>API routes<\/strong>.<\/p>\n\n\n\n<p>To write your backend, add a folder called &#8220;api&#8221; in \/pages to create your own API that are ultimately executed as separate serverless functions.<\/p>\n\n\n\n<p>If we wanted to fetch data for our about page from \/api\/about, we would include a page called about.js in \/pages\/api:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>\/\/ syntax is very similar to the \"Express\" Node.js framework\n\n\/\/ here we are responding to every request with an OK (200) code and sending JSON data back (our name)\n\nexport default function handler(req, res) {\n  res.status(200).json({ name: \"Reed Barger\" });\n}\n<\/code><\/pre>\n\n\n\n<h2 id=\"request-data-client-side\">Request Data Client-side<\/h2>\n\n\n\n<p>Now that we have an API route, how do we use it?<\/p>\n\n\n\n<p>How do we request data from our API routes and use the data in our client pages?<\/p>\n\n\n\n<p>The traditional approach would be to request it using&nbsp;<code>useEffect<\/code>&nbsp;and&nbsp;<code>useState<\/code>:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import Link from \"next\/link\";\nimport { useEffect, useState } from \"react\";\n\nexport default function About() {\n  const &#91;data, setData] = useState(null);\n  const &#91;isLoading, setLoading] = useState(false);\n\n  useEffect(() =&gt; {\n    setLoading(true);\n    fetch(\"api\/about\")\n      .then((res) =&gt; res.json())\n      .then((data) =&gt; {\n        setData(data);\n        setLoading(false);\n      });\n  }, &#91;]);\n\n  if (isLoading) return &lt;p&gt;Loading...&lt;\/p&gt;;\n  if (!data) return &lt;p&gt;No about data&lt;\/p&gt;;\n\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;My name is: {data.name}&lt;\/h1&gt;\n    &lt;\/div&gt;\n  );\n}<\/code><\/pre>\n\n\n\n<p>This approach works, but requires a lot of boilerplate code. On top of that, it doesn&#8217;t have the best user experience.<\/p>\n\n\n\n<p>While this is a basic example, if we had necessary dynamic info to fetch and display in our pages, we would always show the &#8220;Loading&#8221; text to our users on every page visit.<\/p>\n\n\n\n<p>An improved way to fetch data and catch it upon future visit is to use the library SWR, which is also made by the developers of Next.<\/p>\n\n\n\n<p>It gives us a convenient hook&nbsp;<code>useSWR<\/code>&nbsp;to more easily fetch data and handle loading and errors state, as well as cache data for future visits if nothing has changed. If it has changed, fetch the data in the background while the stale data is shown from the cache.<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Note: The hook is named after this &#8220;cache invalidation&#8221; strategy: &#8220;stale-while-revalidate&#8221;<\/p><\/blockquote>\n\n\n\n<p>Here is the same request made using SWR:<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import useSWR from \"swr\";\n\nconst fetcher = (...args) =&gt; fetch(...args).then((res) =&gt; res.json())\n\nexport default function About() {\n  const { data, error } = useSWR(\"\/api\/about\", fetcher)\n\n  if (error) return &lt;div&gt;Error fetching data&lt;\/div&gt;\n  if (!data) return &lt;div&gt;Loading...&lt;\/div&gt;\n\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;{data.name}&lt;\/h1&gt;\n    &lt;\/div&gt;\n  )\n}<\/code><\/pre>\n\n\n\n<h2 id=\"request-data-server-side\">Request Data Server-side<\/h2>\n\n\n\n<p>What&#8217;s an even better way to fetch data in Next that improves user experience and SEO overall?<\/p>\n\n\n\n<p>There are two functions that you can include directly within your page files that allow us to fetch data from the server:<\/p>\n\n\n\n<blockquote class=\"wp-block-quote\"><p>Yes, these functions are in the same file as our React components, but the code for them is bundled separately from our React client.<\/p><\/blockquote>\n\n\n\n<ol><li><code>getServerSideProps<\/code><\/li><li><code>getStaticProps<\/code><\/li><\/ol>\n\n\n\n<h2 id=\"getserversideprops\">GetServerSideProps<\/h2>\n\n\n\n<p><code>getServerSideProps<\/code>&nbsp;runs on every page visit. As a result, it is very helpful on pages with dynamic data or needs requests to be performed every time, such as getting authenticated user data.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export default function About({ name }) {\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;My name is: {name}&lt;\/h1&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport function getServerSideProps() {\n  return {\n    props: { name: \"Reed Barger\" },\n  };\n}<\/code><\/pre>\n\n\n\n<p>The function does exactly as its name states \u2013 it lets us send data from the server and injects it into our page component&#8217;s props.<\/p>\n\n\n\n<p>What is great about this feature is that it allows our React client to display the data immediately, with no delay, plus not have to handle any loading or error state.<\/p>\n\n\n\n<p>If we wanted to fetch data from the server, we could do so by making&nbsp;<code>getServerSideProps<\/code>&nbsp;async using the&nbsp;<code>async<\/code>&nbsp;keyword.<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>export default function About({ name }) {\n  return (\n    &lt;div&gt;\n      &lt;h1&gt;My name is: {name}&lt;\/h1&gt;\n    &lt;\/div&gt;\n  );\n}\n\nexport async function getServerSideProps() {\n  const data = await fetch(\"https:\/\/randomuser.me\/api\").then((res) =&gt;\n    res.json()\n  );\n\n  return {\n    props: { name: data.results&#91;0].name.first },\n  };\n}<\/code><\/pre>\n\n\n\n<p>Here we are dynamically fetching data from the&nbsp;<a href=\"https:\/\/randomuser.me\/\">random user api<\/a>, and our data changes every time we refresh the page.<\/p>\n\n\n\n<h2 id=\"getstaticprops\">GetStaticProps<\/h2>\n\n\n\n<p>Let&#8217;s rename our&nbsp;<code>getServerSideProps<\/code>&nbsp;function with the name&nbsp;<code>getStaticProps<\/code>.<\/p>\n\n\n\n<p>Again, the function does what its name says. Or does it?<\/p>\n\n\n\n<p><code>getStaticProps<\/code>&nbsp;is a function that is more appropriate for more static pages that change less frequently. This function executes our server code and makes a GET request on the server, but it only does so once when our project is built.<\/p>\n\n\n\n<p>When you run the app in development, however, it seems to request data every time we refresh the page like&nbsp;<code>getServerSideProps<\/code>.<\/p>\n\n\n\n<p>It&#8217;s important to note that&nbsp;<code>getStaticProps<\/code>&nbsp;<em>only makes requests on every page visit during development<\/em>.<\/p>\n\n\n\n<p>If you run&nbsp;<code>yarn build<\/code>&nbsp;and then run the production build or your React project using&nbsp;<code>yarn start<\/code>, you will see that no matter how many times we refresh, we keep getting the same name \u2013 the name that was requested when the project was built and not at runtime.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.freecodecamp.org\/news\/content\/images\/2022\/01\/Screen-Shot-2022-01-14-at-3.59.19-PM.png\" alt=\"Screen-Shot-2022-01-14-at-3.59.19-PM\"\/><figcaption>Sample result requested from getStaticProps<\/figcaption><\/figure>\n\n\n\n<p>You might be asking at this point:&nbsp;<em>&#8220;Why use API routes at all with these two functions?&#8221;<\/em><\/p>\n\n\n\n<p>It&#8217;s important to be aware of the fact that both&nbsp;<code>getServerSideProps<\/code>&nbsp;and&nbsp;<code>getStaticProps<\/code>&nbsp;can only perform GET requests. API routes can handle any type of request to read and update data (that is when combined with a data layer like a database)<\/p>\n\n\n\n<h2 id=\"where-to-learn-next-js\">Where to Learn Next.js<\/h2>\n\n\n\n<p>What we&#8217;ve covered here just scratches the surface of Next, but you&#8217;ve already gained everything you need to start using Next in your React projects today.<\/p>\n\n\n\n<p>If you want a more in-depth and technical guide, the official site has an&nbsp;<a href=\"https:\/\/nextjs.org\/learn\/basics\/create-nextjs-app\">interactive course<\/a>&nbsp;on how to learn Next.js from the ground up.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img src=\"https:\/\/www.freecodecamp.org\/news\/content\/images\/2022\/01\/Screen-Shot-2022-01-14-at-12.05.33-PM.png\" alt=\"Screen-Shot-2022-01-14-at-12.05.33-PM\"\/><figcaption>The (free) Next.js Learn Course<\/figcaption><\/figure>\n\n\n\n<p>And if you&#8217;re ready to take the &#8220;Next&#8221; step and want to build full-scale React applications from the ground up, check out&nbsp;<a href=\"https:\/\/reactbootcamp.com\/\"><strong>The React Bootcamp<\/strong><\/a>.<\/p>\n\n\n\n<p>Since you&#8217;re serious about learning React, I&#8217;ve put together a complete, ultimate resource to make you a React pro, ready to:<\/p>\n\n\n\n<ul><li>Build amazing, production-ready apps from start to deploy<\/li><li>Understand React&nbsp;<em>deeply<\/em>&nbsp;from the basic concepts to the latest features<\/li><li>Become an in-demand developer who commands a 6-figure salary<\/li><\/ul>\n\n\n\n<p>If any of these things interest you, check out&nbsp;<a href=\"https:\/\/reactbootcamp.com\/\">The React Bootcamp<\/a>&nbsp;right here:<\/p>\n\n\n\n<p><\/p>\n","protected":false},"excerpt":{"rendered":"<p>The goal of this tutorial is to get you started using Next.js as easily as possible. This is not a complete guide on Next, but it will give you everything you need to understand:<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[30],"tags":[161],"_links":{"self":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2224"}],"collection":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=2224"}],"version-history":[{"count":1,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2224\/revisions"}],"predecessor-version":[{"id":2225,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=\/wp\/v2\/posts\/2224\/revisions\/2225"}],"wp:attachment":[{"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=2224"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=2224"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/lvboard.infostore.in.ua\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=2224"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}