Nextjs 기본부터 알아보자 1

2023. 3. 6. 17:16프론트엔드


What is Next js and Why?

The React Framework for production

React의 “common problems” 를 해결해주는 프레임워크 이다. react의  "common problems"는 SPA로 이루어진 웹앱의 단점이다.

Client Side Rendering

  • 서버에서 한 페이지만 받고 클라이언트에서 렌더링을 하는 방식
  • 기존 리액트 app의 방식
  • 페이지간 이동이 발생하지 않음 : route 방식
  • seo 검색 엔진 최적화에 불리

Server Side Rendering

  • 서버에서 클라이언트에게 전송 후 렌더링하는 방식
  • 페이지간 이동(새로고침)이 발생
  • seo 검색 엔진에 유리
  • next js는 CSR방식의 리액트 앱을 SSR로 전환시켜주는 역할

브라우저 렌더링부터 CSR,SSR,SPA,MPA 정리 까지

 

브라우저 렌더링부터 CSR,SSR,SPA,MPA 정리 까지

생성일: 2023년 1월 14일 오후 6:11 태그: 웹 🏳️ 브라우저 렌더링 ❓ 브라우저 렌더링은 무엇일가요? 일단 나는 브라우저로 크롬을 사용하는 편이다. 크롬이 편리한 기능이 많고, 깔끔하고, 탭관

dev-yeongi.tistory.com

 

in Next JS

  • Atomatic page pre-rendering : Grant for SEO and initial load
  • Blending client side and server side rendering : Fetch data on the server and render finished page

 

File based routing & Page Pre-rendering : automatic routing

  • React js 에서는 라우팅(페이지 이동)을 구현하려면 React router같은 라우팅 라이브러리를 사용해야 핬다.
  • 하지만 Nextjs 에서는 파일 기반 라우터를 제공한다.
  • Define pages and routes with files and folders insteat of code
  • less code, less work , highly undstandable

 

Date Fetch & Adding an API : Fullstack Capabilitys

  • Easily add backend (server side) code to your Next/React apps
  • Storing data, getting data, authentication etc
  • Rest API 방식처럼 굳이 Node js 서버를 따로 구현하지 않아도 된다.

 

그외 특징

 

Building Blocks of a Web Application

There are a few things you need to consider when building modern applications. Such as:

  • User Interface - how users will consume and interact with your application.
  • Routing - how users navigate between different parts of your application.
  • Data Fetching - where your data lives and how to get it.
  • Rendering - when and where you render static or dynamic content.
  • Integrations - what third-party services you use (CMS, auth, payments, etc) and how you connect to them.
  • Infrastructure - where you deploy, store, and run your application code (Serverless, CDN, Edge, etc).
  • Performance - how to optimize your application for end-users.
  • Scalability - how your application adapts as your team, data, and traffic grow.
  • Developer Experience - your team’s experience building and maintaining your application.

nextjs 공식 홈페이지가 참 잘되어 있다.

 

 

install

npx create-next-app 

• If you don’t have Node.js installed, install it from here. You’ll need Node.js version 10.13 or later.

  • NPM 사용을 위해 Nodejs의 설치가 필요하다.

 

page 작성

 

  • pages폴더에 index.js 와 news.js 파일을 생성하고 리액트 컴포넌트를 사용하듯이 코드를 작성해보자
// our-domain.com/

function HomePage() {
  return <h1>Home Page</h1>;
}

export default HomePage;
// our-domain.com/news

function NewsPage() {
  return <h1>The News Page</h1>;
}

export default NewsPage;

저장한 후에 터미널로 코드를 입력한다.

npm run dev

 

  • page에 생성한 파일로 렌더링이 된다. : file route rendering
  • index 파일은 기본 홈페이지(root)로 지정된다 .
  • 그 외의 파일은 파일 이름이 path로 지정된다.

 

  • 폴더로 만들어도 위와 같은 규칙으로 지정 된다.
  • 도메인/news → index.js 렌더링

info/index.js

// our-domain.com/news/info

function NewsInfo() {
  return <h1>The News Info Page</h1>;
}

export default NewsInfo;
  • 폴더안에 파일이나 폴더를 생성하면 중첩 라우팅이 된다.
  • 도메인/news/info → index.js 렌더링

파라미터

  • 동적으로 데이터를 가져오기 위해서 파라미터를 사용해야할 때가 있다.

  • 대괄호로 감싸준 파일을 생성하면 파라미터 페이지를 작성할 수 있다.
// our-domain.com/news/info/[prameter]

function NewsContent() {
  return <h1>The NewsContent Page</h1>;
}

export default NewsContent;
  • param을 추출하기위해 hooks을 사용한다.
import { useRouter } from "next/router";

// our-domain.com/news/info/[prameter]

function NewsContent() {
  //to devalues encoded in url
  const router = useRouter();

  const id = router.query.newsId;

  //서버랑 통신해서 데이터 불러오기
  console.log(router.query, id);

  return <h1>The News Content Page</h1>;
}

export default NewsContent;

 

  • useRouter hook을 사용해서 파일 명으로 추출해서 사용할 수 있다.

 

Navigation

  • 페이지 이동은 어떻게 구현해야 할까?
function HomePage() {
  return (
    <>
      <h1>Home Page</h1>
      <ul>
        <li>
          <a href="/news/info/nextjs-is-framework">NextJs is framework!!</a>
        </li>
        <li>
          <a href="/news/info">info Page</a>
        </li>
      </ul>
    </>
  );
}

export default HomePage;

a 태그를 이용할 시 2가지 단점이 존재함

  • context나 redux의 전역 state를 잃을 수 있음
  • 기존의 ssr 처럼 새로고침현상이 발생함

Link 태그를 이용

// our-domain.com/
import Link from "next/link";

function HomePage() {
  return (
    <>
      <h1>Home Page</h1>
      <ul>
        <li>
          <Link href="/news/info/nextjs-is-framework">
            NextJs is framework!!
          </Link>
        </li>
        <li>
          <Link href="/news/info">info Page</Link>
        </li>
      </ul>
    </>
  );
}

export default HomePage;
  • MPA 방식이 지만 SPA 처럼 라우팅이 됨 ( 새로고침이 안일어남 )
  • SPA 방식이지만 첫페이지가 빨리 렌더링 됨
  • 새로고침이 일어나지 않기 때문에 state를 잃지 않음
  • 부드러운 페이지 이동과 좀 더 좋은 사용자 경험을 줄 수 있음.
  • SPA의 장점과 MPA의 장점을 합쳐 놓은것