• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

Next.js Rendering Patterns

Lomanu4 Оффлайн

Lomanu4

Команда форума
Администратор
Регистрация
1 Мар 2015
Сообщения
1,481
Баллы
155
⚡Next.js Rendering Patterns Explained: Build a Fruit Shop Website ?


If you're new to Next.js or wondering how it makes React even better, you're in the right place! Next.js is a powerful React framework that simplifies building fast, SEO-friendly, and scalable web apps.

One of its biggest strengths? It supports multiple rendering patterns:

  • Static Site Generation (SSG)
  • Client-Side Rendering (CSR)
  • Server-Side Rendering (SSR)
  • Incremental Static Regeneration (ISR)

In this post, we’ll break them down using a real-world example: a fruit shop website. By the end, you’ll know when and how to use each rendering method in your Next.js apps.

? What Is Rendering?


Rendering is how your website’s HTML is prepared and sent to a user’s browser. Think of it as how your fruit shop delivers information to customers visiting its website.

Let’s imagine you run a fruit shop website with these pages:

PageURLDescription
Homepage/Static welcome page (rarely changes).
Dashboard/dashboardUser-specific orders.
News/newsDaily fruit price updates (changes often).
Banana Details/products/bananaBanana price, updated hourly.
? 1. Static Site Generation (SSG) – "Printing a Poster"

What is SSG?


SSG pre-renders HTML at build time. The result is a static file served to all users—fast and SEO-friendly.

? Real-World Analogy:
You print a welcome poster and hang it outside your fruit shop. Everyone sees the same poster until you reprint it.

?‍? Code Example: Homepage (/)


// pages/index.js
export async function getStaticProps() {
return {
props: {
message: "Welcome to the Fruit Shop! Fresh fruits daily!",
},
};
}

export default function Home({ message }) {
return <h1>{message}</h1>;
}
✅ When to Use

  • Static content like homepages, blogs, documentation.
  • Content that changes infrequently.
Pros & Cons


✔ Fastest performance
✔ Great SEO
❌ Requires rebuilds for updates

? 2. Client-Side Rendering (CSR) – "Asking After You Enter"

What is CSR?


CSR loads a blank page and then fetches data in the browser after JavaScript loads.

? Real-World Analogy:
A customer enters your shop and asks, “What are my orders?” The clerk (JavaScript) looks them up and shows the list.

?‍? Code Example: Dashboard (/dashboard)


// pages/dashboard.js
import { useEffect, useState } from 'react';

export default function Dashboard() {
const [orders, setOrders] = useState(null);

useEffect(() => {
fetch('/api/orders') // Simulated API
.then(res => res.json())
.then(data => setOrders(data));
}, []);

return <div>{orders ? orders.join(', ') : 'Loading orders...'}</div>;
}
✅ When to Use

  • Authenticated user pages (dashboards, profiles).
  • Apps where SEO doesn’t matter much.
Pros & Cons


✔ Dynamic, user-specific content
✔ Light server load
❌ Slower initial load
❌ Poor SEO

? 3. Server-Side Rendering (SSR) – "Asking Before Entering"

What is SSR?


SSR renders HTML on the server for every request, ensuring data is always fresh.

? Real-World Analogy:
Before you show the News page, the shop checks the latest prices and prepares the page for the customer.

?‍? Code Example: News (/news)


// pages/news.js
export async function getServerSideProps() {
const res = await fetch('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


const news = await res.json();
return { props: { news } };
}

export default function News({ news }) {
return <div>{news.title}</div>;
}
✅ When to Use

  • Frequently updated pages.
  • Pages requiring SEO + fresh data.
Pros & Cons


✔ Always up-to-date
✔ SEO-friendly
❌ Slower due to per-request rendering
❌ Higher server load

? 4. Incremental Static Regeneration (ISR) – "A Poster That Updates Hourly"

What is ISR?


ISR combines the speed of SSG with scheduled revalidation—regenerating static pages in the background.

? Real-World Analogy:
You hang a banana price poster that updates every hour. Customers always see a poster, and it auto-refreshes behind the scenes.

?‍? Code Example: Banana Details (/products/banana)


// pages/products/banana.js
export async function getStaticProps() {
const res = await fetch('

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.


const banana = await res.json();
return {
props: { banana },
revalidate: 3600, // Regenerate every hour
};
}

export default function Banana({ banana }) {
return <h1>Banana Price: ${banana.price}</h1>;
}
✅ When to Use

  • Product pages, marketing pages, or feeds.
  • Content updated on a regular schedule.
Pros & Cons


✔ Static speed + freshness
✔ SEO-friendly
❌ Slightly stale data between regenerations

? Rendering Pattern Comparison

PatternFreshnessSpeedServer LoadBest For
SSG❌ Fixed✅ Fastest✅ LowStatic pages (Homepage)
CSR✅ Client-side❌ Slower✅ LowUser dashboards
SSR✅ Real-time❌ Slower❌ HighReal-time data (News)
ISR✅ Periodically✅ Fast✅ MediumProduct pages (Banana Details)
? Mix & Match Patterns in One App


That’s the beauty of Next.js—you can use all four patterns in one project:

  • ? Use SSG for the Homepage
  • ? Use CSR for the Dashboard
  • ? Use SSR for the News page
  • ? Use ISR for the Banana Details page
? Why Use Next.js Instead of React Alone?


React is awesome for building UIs but focuses only on Client-Side Rendering (CSR). To add SSR or SSG, you'd need tools like Gatsby or custom setups.

Next.js simplifies it all:

  • Built-in support for SSR, SSG, ISR, and CSR
  • File-based routing (pages/)
  • Built-in SEO tools and performance optimizations
  • Freedom to mix rendering strategies per page
? Ready to Build Your Fruit Shop?


Start in minutes:


npx create-next-app@latest my-fruit-shop
cd my-fruit-shop
npm run dev

Then create pages like:

  • pages/index.js for SSG
  • pages/dashboard.js for CSR
  • pages/news.js for SSR
  • pages/products/banana.js for ISR

When you're ready to deploy:


npm run build
npm run start
? Final Thoughts


Next.js gives you powerful rendering tools to optimize for speed, SEO, and scalability. Whether you’re building a blog, dashboard, or online store—there’s a rendering pattern for every use case.

Happy coding! ?


Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу