본문 바로가기
Personal-Study/Next.js

[Next.js 13 공식 문서 App Router] - React Essentials

by Aaron-Kim 2023. 8. 24.

React Essentials

Server Components

- Thinking in Server Components

  - The majority of components are non-interactive and can be rendered on the server

  - Next.js Server-first approach

- Why Server Components?

  - We can move data fetching to the server

  - The initial page load is faster, client-side js bundle size reduced

  - The base client-side runtime is cacheable and predictable

  - All components inside App Router are Server Components by default

Client Components

- The 'use client' directive

  - 'use client' sits between server-only and client code

When to use Server and Client Components?

  - Sever Component

    - Fetch data

    - Access backend resources (directly)

    - Keep sensitive information on the server (access tokens, API keys, etc.)

    - Keep large dependencies on the server / Reduce client-side JS

  - Client Component

    - Add interactivity and event listeners (onClick, onChange etc.)

    - Use State and Lifecycle Effects (useState, useReducer, useEffect etc.)

    - Use browser-only APIs

    - Use custom hooks that depend on state, etffects, or browser-only APIs

    - Use React Class commponents

Patterns

- Moving Client Components to the Leaves

- Composing Client and Server Components

  - In Next.js, during the initial page load, both the rendered result of Server components
     and Client components are pre-rendered on the server as HTML to produce a faster initial page load

- Nesting Server Components inside Client Components

  - Unsupported Pattern: Importing Server Components into Client Components (Not work)

  - Recommended Pattern: Passing Server Components to Client Components as Props

- Passing Props from Server to Client Components (Serialization)

- Keeping Server-Only Code out of Client Components (Poisioning)

- The 'server only' package

  - npm install server-only

- Data Fetching

  - Recommend fetching data in Server Components

- Third-party packages

  - We can wrap third-party components that rely on client-only features in your own Client components

Context

- Using context in Client Components

  - Create our context and render its provider inside of a Client Component

- Rendering third-party context providers in Server Components

  - Wrap third-party providers in our own Client Component

- Sharing data between Server Components

  - JS pattern called global singletons (import)

- Sharing fetch requests between Server Components

  - fetch requests are automatically memoized in Server Components

  - Next.js will read the same value from the fetch cache

반응형

댓글