Beginners Guide To NextJs
Pherus
Beginners Guide To NextJs
Building web apps can feel complicated and often we get stuck on all the options out there for building them. This is just one girl’s perspective on the tech and specs she likes, but let me tell you, many of these tools have been tried and tested by me for years in personal and professional projects, so it’s a solid rec 😺
Here is an example application using the technologies and practices outlined in this article:
We’ll cover some core areas
- Environment setup
- Start
- Understanding the code
- Component libraries
- Hooks and the Component Lifecycle
Environment setup
Language | Typescript with React library
Compile & Deploy | Node
Package manager | Yarn (read understanding node, nvm, and npm)
Text Editor | VSCode
Debug on | Chrome
Simple as that, right?
Not quite, we need to understand how all these tools and technologies work with each other to render a beautiful web page.
Language: Typescript with React library and Next.js framework
TypeScript (TS) casts a stricter enforcement of data types onto our code, which is used to structure the compiled version of JavaScript (JS) — enabling us to catch more bugs when building the code.
React offers us a structure to build in a component-based architecture so that we have reusable and shareable components. The library aids in creating defined avenues for routing, querying, rendering at varying times, extrapolating JS into a far more readable and concise language.
We use TS and React to wrangle the JS beast.
Next.js is a framework we will use to handle configuring React to be more structured and seamless when building the app. It eases the challenges of implementing routing, data fetching, and caching for React apps and employs server-side rendering for most of the functionality, unless we specify to render from the client side.
Compile & Deploy: Node
Ah yes, my love, Node. Node is a beautiful framework that enables JS to be built in the backend and create a cohesive fullstack application within a
single language
. Everything can be compiled and deployed at once, making frontend and backend development far more seamless.
Head to nodejs.org to download the latest version of Node. After installation, confirm node is downloaded with:
1node -v
2npm -v
Package Manager: Yarn
A package manager helps us contain and organize our node project into smaller more succinct modules. The debate between NPM and Yarn is one that will outlast my career, but my two cents are that while both
can
do the same functionality, Yarn is faster (read more here).
Head to classic.yarnokg.com to install Yarn. You can use npm to install yarn (which was installed with Node) or an alternative like homebrew or a curl script. After installation, confirm yarn is downloaded with:
1yarn -v
NVM (Optional)
You can use
nvm
to manage the node version for individual projects since some project dependencies may require a different version of Node.
Head to this guide to install NVM, if you run into any issues you can review the README for nvm to troubleshoot. After installation, confirm nvm is downloaded with:
1nvm -v
I suggest setting the latest version of Node to the default with the below commands, then exit and open a new tab in terminal for the configuration to be set:
1nvm alias default node
2nvm use default
Text Editor: VSCode
This is the best editor! There, I said it! Come at me 👊 Here’s a helpful guide for setting up your editor
Obviously everyone has their preference, but I LOVE the visual aids it has
for viewing your code in a tree structure (far more helpful than you’d expect), seeing the diffs on code changes, and if you’re lazy like me sometimes making your commits from the editor 😬
Here’s an example of one of VSCode’s awesome visuals — it’s highlighting the commit changes when I added Material UI NextJS integrations to the codebase:
// image
Debug on: Chrome
Chrome or Firefox are good choices for debugging code, both have quality inspectors to see code structure, console errors, network events, local and session storage, React components structure, analytics tabs and much more! Throw a pointer in there and start debugging (read more here).
Start
1.Navigate in your terminal where you’d like to store your projectcd ~/code
2. We’ll follow Reacts how-to guide for spinning up a React app with Next.jsnpx create-next-app@latest
3. This will ask you a series of questions — name your project and press enter
for each of the questions to initialize a basic app
4. Navigate into the application directory and open it in VSCodecd elana-olson-react-next-app
code .
// opens VSCode from terminal
5. Now let’s serve this baby up and see what we’re working with! Navigate to the README.md
and press ⇧⌘V
in the editor to preview the markdown.
// image
The README.md
tells us to run the development server, type into the terminalyarn dev
6. Once you see
✓
Ready
in the terminal, navigate to http://localhost:3000 in Chrome and you’ll see something like this:
// image
Understanding the Code
You can read this code in github in the example app:
Let’s investigate the initialized files, Next.js documents the project structure well , but we’ll briefly review what the top level files and folders are for.
.next
| Stores features that help with performance like page caching
node_modules
| Stores the packages and dependencies defined in package.json
public
| Stores publicly accessible files like assets (images)
src
| Stores all our custom source code 💚
.eslintrc.json
| Configuration for ESLint. ESLint helps us define specific patterns for JavaScript and catch problematic patterns before deploying.
.gitignore
| Defines which files/folders not to publish to the repository. Files and folders like node_modules
which are far too big to publish or secret files that would expose vulnerable credentials.
next-env.d.ts
| TypeScript declaration for Next.js
next.config.mjs
| Configuration for Next.js
package.lock.json
| Automatically generated by the package manager… don’t manually change this file.
package.json
| Defines project scripts and dependencies to enable us to run the project
postcss.config.js
| Configuration for css
README.md
| An engineer’s “How To” guide and
crucial
documentation for how to use this project
tailwind.config.ts
| Configuration for tailwind css
tsconfig.json
| Configuration of TypeScript strictness, structure, and compiler
README, package.json, & tsconfig.json
The most important files to review in any project are: README.md
, package.json
, & tsconfig.json
, though all configuration files will impact the structure and strictness of your code.
The scripts
section defines what commands we run in the terminal to develop, compile, start, and analyzing code for potential errors. For each of them, type Yarn
in front of it to run the script.
Notice that we are on the latest versions of React, React-dom, and Next — this is a good practice to follow of staying up to date with all dependencies, but especially the foundational libraries and frameworks.
In the tsconfig.json
we want to pay attention to module
and moduleResolution
— these two define how TypeScript scopes global and local state (i.e. Modulaization determines whether a variable in a file is readable and usable outside of that file or package). Using moduleResolution: bundler
allows us to define global state via "imports"
and "exports"
without needing file extensions on relative paths. You can read more here to further understand module theory and how to apply it to your app.
src/
Now that you understand the root level files, take a look into the src/
folder (otherwise known as app). The key files here are layout.tsx
and page.tsx
—
Next.js uses pages and layouts to define routes and components in the app.
Pages
In Next.js, a page is a React Component exported from a
.js
,.jsx
,.ts
, or.tsx
file in thepages
directory. Each page is associated with a route based on its file name.
We can think of pages as routes and the pages
directory as the root folder/home for all our routes. So if you want to create an About page on your website, it would be accessed at /about
and housed in the codebase under pages/about.ts
.
Layouts
The React model allows us to deconstruct a page into a series of components. Many of these components are often reused between pages. For example, you might have the same navigation bar and footer on every page.
Layouts enable us to create reusable patterns for our app, either for the entire app or per-page.
Next.js details an excellent guide to Page and Layout usage.
Component libraries
A component library is a set of frontend reusable components that are frequently used throughout an application. The library
should
follow accessibility standards, themes, and enable you to quickly plug and play components into your app so you don’t have to create entirely new basic components like buttons and menus.
The cons to a library are: you need to familiarize yourself with all the components and there are limitations to what those components will do — they will not cover every edge case or design that you have in mind. In cases where you’re building a very simple app, a component library could be a hindrance, but component libraries can be powerful tools once learned!
Checkout these various UI libraries or incorporate one you are already familiar with! The point of using one is to speed along your coding, so go with something you like.
Material UI (Optional)
Here’s a short article I wrote detailing how to integrate material ui into a react nextjs app.
Hooks and the Component Lifecycle
Now that we have an army of tools at our command, we need to understand how to wield them…. so the render cycle is of utmost importance! “Hooks are functions that let you “hook into” React features like state, lifecycle methods, and context from your function components,” (The Power of React Hooks).
We can tap into the React render lifecycle in the three phases — mount, update, unmount — using hooks. The mount phase allows us to insert elements into the DOM, set initial state, and load the elements on the first render. The update phase occurs when props or state changes and we need to update the component, which retriggers the render() function. Finally, the unmount phase removes the react component from the DOM and cleans up any related state.
I suggest reading The Lifecycle of a React Component to understand what React methods are called during these phases. When using hooks, we don’t call the React functions likegetDerivedStateFromProps()
directly, the hooks do this for us. Hooks like useState
will initialize, update, and clean state for us as we use the component. The article React Component Lifecycle Methods with React Hooks outlines this relationship and how to transition your use of lifecycle methods to hooks.
The key takeaways here are (1) we need to understand the lifecycle of a React component to know how to update data and (2) hooks help us do this smoothly.
Checkout React’s docs to thoroughly understand the usage of hooks.
That’s all folks! If you think I’ve missed anything or you gave this tutorial a whirl, please leave some feedback! Hope this helps you enter the wonderful world of React coding 😺
Related Posts
The meaning of the word or name Pherus ? , is rather symbolic than meaningful the context of its symbolism is what matters.