From 31b960cb047b719b226c070382f6ed30dce257c8 Mon Sep 17 00:00:00 2001 From: ogechi uhegbu Date: Thu, 30 Jul 2026 17:19:13 +0100 Subject: [PATCH 1/4] add article on introduction to next --- next/Introduction-to-nextjs.md | 54 ++++++++++++++++++++++++++++++++++ next/README.md | 21 +++++++++++++ 2 files changed, 75 insertions(+) create mode 100644 next/Introduction-to-nextjs.md create mode 100644 next/README.md diff --git a/next/Introduction-to-nextjs.md b/next/Introduction-to-nextjs.md new file mode 100644 index 0000000..07adc37 --- /dev/null +++ b/next/Introduction-to-nextjs.md @@ -0,0 +1,54 @@ +# Title of Your Article + +> **Topic:** React · **Level:** Beginner | Intermediate | Advanced · **Author:** [@yourhandle](https://github.com/yourhandle) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/README.md b/next/README.md new file mode 100644 index 0000000..f7688b4 --- /dev/null +++ b/next/README.md @@ -0,0 +1,21 @@ +# React + +React patterns, anti-patterns, and best practices from production codebases. + +## Articles + + + +*No articles yet — [be the first to contribute!](../CONTRIBUTING.md)* + +## Ideas for Contributions (but not limited to) + +- Component composition patterns (compound components, render props, slots) +- Error boundaries in practice +- Custom hooks: when to extract, when not to +- Server components and data fetching strategies +- Re-render debugging and `memo`/`useMemo` done right +- Form handling patterns at scale +- Anti-patterns you've seen (and fixed) in real codebases + +See [CONTRIBUTING.md](../CONTRIBUTING.md) for the article format, and copy [the template](../templates/article-template.md) to get started. From a8aa9e5974a493c0994866a0f8c65f4ce5f1a2d0 Mon Sep 17 00:00:00 2001 From: ogechi uhegbu Date: Fri, 31 Jul 2026 00:25:31 +0100 Subject: [PATCH 2/4] initial commit for next beginners topics --- README.md | 2 + next/Introduction-to-nextjs.md | 390 ++++++++++++++++++- next/README.md | 15 +- next/Understanding-Routing-in-Next.js.md | 55 +++ next/file-colocation-in-next.md | 55 +++ next/loading-UI-in-next.md | 55 +++ next/not-found-page-in-next.js.md | 55 +++ next/private-folder.md | 55 +++ next/templates-file-in-next.md | 55 +++ next/understanding-error-handling-in-next.md | 55 +++ next/understanding-layout-in-nextjs.md | 55 +++ next/understanding-metadata-in-next.md | 55 +++ 12 files changed, 897 insertions(+), 5 deletions(-) create mode 100644 next/Understanding-Routing-in-Next.js.md create mode 100644 next/file-colocation-in-next.md create mode 100644 next/loading-UI-in-next.md create mode 100644 next/not-found-page-in-next.js.md create mode 100644 next/private-folder.md create mode 100644 next/templates-file-in-next.md create mode 100644 next/understanding-error-handling-in-next.md create mode 100644 next/understanding-layout-in-nextjs.md create mode 100644 next/understanding-metadata-in-next.md diff --git a/README.md b/README.md index 1bf5805..ba679ab 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ That knowledge usually lives in private Slack threads, internal docs, and the he | Section | What's Inside | |---|---| | [`react/`](react/) | React patterns, anti-patterns, and best practices | +| [`next/`](next/) | Next patterns, anti-patterns, and best practices | | [`typescript/`](typescript/) | TypeScript techniques, type design, and gotchas | | [`architecture/`](architecture/) | Frontend architecture, project structure, and design decisions | | [`performance/`](performance/) | Performance optimization strategies and measurement | @@ -80,6 +81,7 @@ All contributions follow a consistent structure so the knowledge base stays high ```text frontend-engineering-lab/ ├── react/ +├── next/ ├── typescript/ ├── architecture/ ├── performance/ diff --git a/next/Introduction-to-nextjs.md b/next/Introduction-to-nextjs.md index 07adc37..6dbdf2d 100644 --- a/next/Introduction-to-nextjs.md +++ b/next/Introduction-to-nextjs.md @@ -1,6 +1,9 @@ -# Title of Your Article + beginner-friendly article introducing Next.js. It explains why Next.js exists(react using react you have to install third part libring for routing), its core features, how to create a new project, the basic project structure, a simple "Hello, World!" example, and the tradeoffs of using the framework. +Your main content. Explain the pattern, technique, or approach. + +# Introduction to Next.js -> **Topic:** React · **Level:** Beginner | Intermediate | Advanced · **Author:** [@yourhandle](https://github.com/yourhandle) +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) *No articles yet — [be the first to contribute!](../CONTRIBUTING.md)* diff --git a/next/Understanding-Routing-in-Next.js.md b/next/Understanding-Routing-in-Next.js.md new file mode 100644 index 0000000..12d84c3 --- /dev/null +++ b/next/Understanding-Routing-in-Next.js.md @@ -0,0 +1,55 @@ +beginner-friendly article on routing in Next.js using the App Router. It covers file-based routing, nested and dynamic routes, route parameters (params), query parameters (searchParams), active links, programmatic navigation, and routing best practices with practical examples. +# understanding routing in next + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution +beginner-friendly article on routing in Next.js using the App Router. It covers file-based routing, nested and dynamic routes, route parameters (params), query parameters (searchParams), active links, programmatic navigation, and routing best practices with practical examples. +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/file-colocation-in-next.md b/next/file-colocation-in-next.md new file mode 100644 index 0000000..bc93c9f --- /dev/null +++ b/next/file-colocation-in-next.md @@ -0,0 +1,55 @@ +This PR adds a new beginner-friendly article explaining file colocation in the Next.js App Router. It covers what file colocation is, why it is useful, how it works, practical examples, trade-offs, and best practices. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/loading-UI-in-next.md b/next/loading-UI-in-next.md new file mode 100644 index 0000000..05c5872 --- /dev/null +++ b/next/loading-UI-in-next.md @@ -0,0 +1,55 @@ +This PR adds a new beginner-friendly article explaining how to implement loading UI in the Next.js App Router using the loading.tsx convention. It covers the problem, solution, practical examples, best practices, tradeoffs, and key takeaways to help developers improve the user experience during route navigation and data fetching. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/not-found-page-in-next.js.md b/next/not-found-page-in-next.js.md new file mode 100644 index 0000000..4940ff7 --- /dev/null +++ b/next/not-found-page-in-next.js.md @@ -0,0 +1,55 @@ +beginner-friendly article explaining how to create and use custom Not Found (404) pages in the Next.js App Router. It covers creating a global not-found.tsx, handling missing resources with notFound(), route-specific not-found pages, best practices, tradeoffs, and practical code examples. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/private-folder.md b/next/private-folder.md new file mode 100644 index 0000000..aa422d1 --- /dev/null +++ b/next/private-folder.md @@ -0,0 +1,55 @@ +Adds a new beginner-friendly article explaining Private Folders in Next.js, covering what they are, how they work, and how to use a route-specific _lib private folder to organize implementation details without affecting routing +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/templates-file-in-next.md b/next/templates-file-in-next.md new file mode 100644 index 0000000..0b696e6 --- /dev/null +++ b/next/templates-file-in-next.md @@ -0,0 +1,55 @@ +This PR adds a new beginner-friendly article explaining Template Files (template.tsx) in the Next.js App Router. It covers what templates are, how they differ from layouts, common use cases, tradeoffs, and includes practical code examples. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/understanding-error-handling-in-next.md b/next/understanding-error-handling-in-next.md new file mode 100644 index 0000000..1410fea --- /dev/null +++ b/next/understanding-error-handling-in-next.md @@ -0,0 +1,55 @@ +This PR adds a new beginner-friendly article, "Understanding Error Handling in Next.js", covering how to handle errors using the App Router. It explains route-level error boundaries with error.tsx, recovering from errors using reset(), handling errors in nested routes, global error handling with global-error.tsx, best practices, tradeoffs, and practical code examples. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/understanding-layout-in-nextjs.md b/next/understanding-layout-in-nextjs.md new file mode 100644 index 0000000..44523dd --- /dev/null +++ b/next/understanding-layout-in-nextjs.md @@ -0,0 +1,55 @@ +add the Understanding Layouts in Next.js article with a more comprehensive explanation of layouts in the App Router. This includes improved examples of root, nested, and multiple root layouts, before-and-after code comparisons, tradeoffs, key takeaways, and updated references to the official Next.js documentation. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/understanding-metadata-in-next.md b/next/understanding-metadata-in-next.md new file mode 100644 index 0000000..4b15db7 --- /dev/null +++ b/next/understanding-metadata-in-next.md @@ -0,0 +1,55 @@ +This PR adds a beginner-friendly article explaining the Next.js Metadata API, including static and dynamic metadata, routing metadata, title templates, and Open Graph metadata with practical examples and best practices. +# Introduction to Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + + + +## The Problem + +What problem does this solve? Why should the reader care? + +Describe the situation a developer is in when they need this knowledge. Make it concrete. + +## The Solution + +Your main content. Explain the pattern, technique, or approach. + +```tsx +// Keep code examples focused and production-oriented. +// Show the relevant part, not the whole app. +``` + +If you're demonstrating an improvement, show **before** and **after**: + +```tsx +// Before +``` + +```tsx +// After +``` + +## Tradeoffs + +No solution is free. Be honest about the costs: + +- **When this shines:** ... +- **When to avoid it:** ... +- **What you give up:** ... + +## Key Takeaways + +- 3–5 bullet points the reader should remember +- Each should stand on its own +- Think: "what would I tell a teammate in 30 seconds?" + +## References *(optional)* + +- [Link to docs, talks, or articles that go deeper](https://example.com) From 3fbe2e49664f54f0560a80348f06b5995bd4ee0d Mon Sep 17 00:00:00 2001 From: ogechi uhegbu Date: Fri, 31 Jul 2026 00:29:39 +0100 Subject: [PATCH 3/4] update readme file in next folder --- next/README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/next/README.md b/next/README.md index 50afb2c..3612b7d 100644 --- a/next/README.md +++ b/next/README.md @@ -14,11 +14,8 @@ Next patterns, anti-patterns, and best practices from production codebases. - [Templates file in Next](./templates-file-in-next.md) - [Loading UI in Next](./loading-UI-in-next.md) - [Understanding Error handling in Next](./understanding-error-handling-in-next.md) - -*No articles yet — [be the first to contribute!](../CONTRIBUTING.md)* - ## Ideas for Contributions (but not limited to) - Component composition patterns (compound components, render props, slots) From b69961f83258c8191fef58d2f6c2dee6485474e1 Mon Sep 17 00:00:00 2001 From: ogechi uhegbu Date: Fri, 31 Jul 2026 12:01:17 +0100 Subject: [PATCH 4/4] create ten(10) next beginner's topics --- next/Introduction-to-nextjs.md | 401 ++++++---------- next/README.md | 10 +- next/Understanding-Routing-in-Next.js.md | 55 --- next/custom-not-found-pages-in-nextjs.md | 184 ++++++++ next/error-handling-in-nextjs.md | 292 ++++++++++++ next/file-colocation-in-next.md | 177 +++++-- next/loading-UI-in-next.md | 189 ++++++-- next/not-found-page-in-next.js.md | 55 --- next/private-folder.md | 112 +++-- next/routing-mechanism-in-nextjs.md | 463 +++++++++++++++++++ next/templates-file-in-next.md | 229 +++++++-- next/understanding-error-handling-in-next.md | 55 --- next/understanding-layout-in-nextjs.md | 299 ++++++++++-- next/understanding-metadata-in-next.md | 55 --- next/using-metadata-in-next.md | 239 ++++++++++ 15 files changed, 2194 insertions(+), 621 deletions(-) delete mode 100644 next/Understanding-Routing-in-Next.js.md create mode 100644 next/custom-not-found-pages-in-nextjs.md create mode 100644 next/error-handling-in-nextjs.md delete mode 100644 next/not-found-page-in-next.js.md create mode 100644 next/routing-mechanism-in-nextjs.md delete mode 100644 next/understanding-error-handling-in-next.md delete mode 100644 next/understanding-metadata-in-next.md create mode 100644 next/using-metadata-in-next.md diff --git a/next/Introduction-to-nextjs.md b/next/Introduction-to-nextjs.md index 6dbdf2d..68b68ce 100644 --- a/next/Introduction-to-nextjs.md +++ b/next/Introduction-to-nextjs.md @@ -1,161 +1,85 @@ - beginner-friendly article introducing Next.js. It explains why Next.js exists(react using react you have to install third part libring for routing), its core features, how to create a new project, the basic project structure, a simple "Hello, World!" example, and the tradeoffs of using the framework. -Your main content. Explain the pattern, technique, or approach. - -# Introduction to Next.js - -> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - - -## The Problem - -What problem does this solve? Why should the reader care? - -Describe the situation a developer is in when they need this knowledge. Make it concrete. -what react can't solve - -## The Solution - - -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. -``` - -If you're demonstrating an improvement, show **before** and **after**: - -```tsx -// Before -``` - -```tsx -// After -``` - -## Tradeoffs - -No solution is free. Be honest about the costs: - -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... - -## Key Takeaways - -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" - -## References *(optional)* - -- [Link to docs, talks, or articles that go deeper](https://example.com) - - - - - - - - - - - - - - - - - - - - # Introduction to Next.js > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) ## The Problem -React is one of the most popular libraries for building user interfaces. It makes it easy to create reusable components and interactive web applications. +React is one of the most popular libraries for building user interfaces. It makes it easy to create reusable components and build interactive web applications. -However, React only focuses on building the **UI (User Interface)**. It doesn't provide everything you need to build a complete production-ready application. +However, React focuses only on the **view layer** of an application. It doesn't provide everything required to build a complete production-ready application. -When building a real-world application with React, you'll often need to figure out things like: +When building a real-world React application, you'll often need additional tools for: -- Routing between pages -- Server-side rendering (SSR) -- Static site generation (SSG) +- Routing +- Data fetching - Search Engine Optimization (SEO) - Image optimization +- Authentication +- Server-side rendering - API endpoints -- Code splitting and performance optimization -- File-based project organization +- Performance optimization -To solve these problems, developers usually install and configure several libraries such as React Router, Express, Vite plugins, image optimization libraries, authentication solutions, and more. +To add these features, developers typically install and configure multiple third-party libraries such as React Router, TanStack Query, authentication libraries, image optimization tools, and more. -As an application grows, managing all these tools can become difficult and time-consuming. +As your application grows, managing all these tools can become complex and time-consuming. -This is where **Next.js** comes in. +This is where **Next.js** helps. -Next.js is a React framework that provides many of these features out of the box, allowing developers to focus more on building applications instead of configuring tooling. - ---- +Next.js is a React framework that provides many of these features out of the box, allowing you to focus on building your application instead of configuring your tooling. ## The Solution ### What is Next.js? -Next.js is an open-source framework built on top of React by **Vercel**. +Next.js is an open-source React framework created by **Vercel**. -It extends React with features that make building production-ready web applications much easier. +It extends React with features that make building modern, production-ready web applications faster and easier. -Some of its most popular features include: +Some of the core features include: - File-based routing -- Server-side rendering (SSR) -- Static Site Generation (SSG) -- Incremental Static Regeneration (ISR) -- API Routes -- Built-in image optimization -- Automatic code splitting -- Metadata management for SEO +- Server Components and Client Components +- Multiple rendering strategies (SSR, SSG, ISR, CSR) +- Built-in data fetching +- Route Handlers for building APIs +- Image optimization +- Font optimization +- Script optimization +- Metadata API for SEO - TypeScript support -- Fast Refresh during development - -Instead of spending hours configuring your project, Next.js gives you sensible defaults that work immediately. +- Fast Refresh +- Production-ready build system ---- +Instead of installing and configuring many libraries yourself, Next.js provides sensible defaults and conventions that help you build scalable applications. -## Creating Your First Next.js Project +### Creating Your First Next.js Project -You can create a new Next.js application using the following command: +Create a new project using: ```bash npx create-next-app@latest ``` -Or using npm: +or ```bash npm create next-app@latest ``` -The installer will ask a few questions: +You'll be asked a few questions during installation: ```text ✔ What is your project named? ✔ Would you like to use TypeScript? ✔ Would you like to use ESLint? ✔ Would you like to use Tailwind CSS? +✔ Would you like your code inside a src/ directory? ✔ Would you like to use the App Router? +✔ Would you like to use Turbopack? +✔ Would you like to customize the import alias? ``` -After installation, navigate into the project: +Navigate into your project: ```bash cd my-next-app @@ -167,76 +91,90 @@ Start the development server: npm run dev ``` -Open your browser and visit: +Visit: ``` http://localhost:3000 ``` -You should see your new Next.js application running. +Your first Next.js application should now be running. ---- +### Understanding the Project Structure -## Understanding the Project Structure - -A new Next.js project contains several folders and files. +A typical Next.js project looks like this: ```text my-next-app/ -│ + ├── app/ │ ├── layout.tsx │ ├── page.tsx +│ ├── globals.css │ ├── public/ -│ ├── components/ -│ -├── styles/ -│ +├── lib/ +├── next.config.ts ├── package.json -└── next.config.ts +└── tsconfig.json ``` -### Important folders - #### `app/` -This is where your application pages live when using the App Router. +The `app` directory contains your application's routes. -Every folder inside `app` can represent a route. +Each folder represents a route, and every route must contain a `page.tsx` file. Example: ```text app/ - page.tsx - about/ - page.tsx +│ +├── page.tsx +├── about/ +│ └── page.tsx +└── contact/ + └── page.tsx ``` Creates: ``` / +/about +/contact ``` -and +#### `layout.tsx` -``` -/about -``` +A layout wraps pages and is shared across multiple routes. ---- +Instead of repeating common UI like navigation bars or footers on every page, you define them once inside a layout. + +Example: + +```tsx +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} +``` #### `public/` Stores static assets such as: -- images -- videos -- icons -- fonts +- Images +- Videos +- Fonts +- Icons Example: @@ -244,44 +182,41 @@ Example: public/logo.png ``` -Can be accessed with: +Use it like this: ```tsx Logo ``` ---- - #### `components/` -A common place to keep reusable UI components. +A common place to store reusable UI components. Example: ```text components/ - Button.tsx Navbar.tsx Footer.tsx + Button.tsx ``` ---- +#### `lib/` -#### `package.json` +Many developers use this folder for shared utilities such as: -Contains project information and dependencies. - ---- +- API clients +- Database functions +- Helper functions +- Validation schemas #### `next.config.ts` -Used to configure Next.js behavior. - ---- +Contains project-specific Next.js configuration. -## Your First Page +### creating your first Next.js page -Inside the `app` folder you'll find: +Create the following page inside `app/page.tsx`: ```tsx export default function Home() { @@ -289,150 +224,104 @@ export default function Home() { } ``` -Visiting: +Visit: ``` http://localhost:3000 ``` -renders: +You'll see: -```text +``` Hello, World! ``` -That's your first Next.js page. +Congratulations! You've created your first Next.js page. ---- +### Client Components vs Server Components -## File-Based Routing +By default, every component in the `app` directory is a **Server Component**. -One of Next.js's biggest advantages is that routing is based on the file system. +Server Components render on the server before being sent to the browser. They can fetch data directly and reduce the amount of JavaScript sent to the client. -Instead of writing route configurations manually, you simply create folders. +If a component needs browser features such as: -For example: +- `useState` +- `useEffect` +- Event handlers (`onClick`) +- Browser APIs (`localStorage`, `window`, etc.) -```text -app/ - about/ - page.tsx -``` - -Automatically creates: +you must mark it as a **Client Component** using the `"use client"` directive. -``` -/about -``` +Example: -Another example: +```tsx +"use client"; -```text -app/ - contact/ - page.tsx -``` +import { useState } from "react"; -Creates: +export default function Counter() { + const [count, setCount] = useState(0); + return ; +} ``` -/contact -``` - -No additional router configuration is needed. ---- +#### What about `"use server"`? -## Example: React vs Next.js Routing +Unlike `"use client"`, you usually **do not need** to add `"use server"` to regular Server Components because they are server-rendered by default. -### Before (React) +The `"use server"` directive is primarily used to define **Server Actions**, allowing functions to execute securely on the server. -In a typical React application, you usually configure routes yourself. +Example: ```tsx -import { BrowserRouter, Routes, Route } from "react-router-dom"; - - - - } /> - } /> - -; -``` - -### After (Next.js) - -Simply create the folder structure: +"use server"; -```text -app/ - page.tsx - about/ - page.tsx +export async function createPost(formData: FormData) { + // Save data to the database +} ``` -Next.js automatically creates the routes for you. +### Why Developers Like Next.js ---- - -## Why Developers Like Next.js - -Next.js reduces the amount of setup required for modern web applications. - -Instead of combining many separate libraries, it provides a complete framework with features such as: +Next.js simplifies modern web development by providing: - Better SEO through server rendering -- Faster page loading -- Optimized images - Built-in routing -- API endpoints -- Automatic performance optimizations -- Excellent developer experience - -These features make it suitable for blogs, portfolios, dashboards, e-commerce websites, company websites, SaaS applications, and many other types of projects. - ---- - -## Tradeoffs - -No solution is perfect. +- Optimized images and fonts +- Fast page loading +- API development with Route Handlers +- Automatic code splitting +- Streaming and Server Components +- Great developer experience -### **When this shines:** +These features make it an excellent choice for: -- Building production-ready React applications -- Applications that need SEO -- Content-heavy websites -- E-commerce platforms +- Blogs +- Portfolios +- Company websites +- SaaS products +- Dashboards +- E-commerce applications - Marketing websites -- Dashboards and SaaS products - -### **When to avoid it:** - -- Small learning projects where plain React is enough -- Applications that don't need server rendering or SEO -- Teams that only need a simple client-side application -### **What you give up:** - -- More concepts to learn compared to React alone -- Build and rendering strategies (SSR, SSG, ISR, CSR) -- A framework with opinions about project structure -- Slightly larger learning curve for beginners +## Tradeoffs ---- +- **When this shines:** Best for Production-ready React applications, SEO-focused websites, Large-scale applications, E-commerce, SaaS products, and Content-heavy websites. +- **When to avoid it:** Small React learning projects, Simple single-page applications that don't require SEO or server rendering, and Teams that only need client-side rendering. +- **What you give up:** More concepts to learn than React alone, Different rendering strategies (SSR, SSG, ISR, CSR, RSC), A framework with conventions and opinions and Slightly steeper learning curve ## Key Takeaways -- React builds user interfaces, while Next.js provides a complete framework for building production-ready React applications. -- Next.js includes features like routing, rendering strategies, image optimization, API routes, and SEO support out of the box. -- File-based routing makes creating pages simple—adding a folder with a `page.tsx` file automatically creates a route. -- Creating a new Next.js project is quick with `create-next-app`, allowing you to start building immediately. -- Next.js is an excellent choice for applications where performance, SEO, and developer productivity are important. - ---- +- React is a library for building user interfaces, while Next.js is a full React framework for building production-ready applications. +- Next.js provides routing, rendering strategies, data fetching, optimization, and API capabilities out of the box. +- The App Router uses file-based routing, making navigation simple and intuitive. +- Components are Server Components by default; use `"use client"` only when browser interactivity is required. +- Next.js helps developers build faster, more scalable, and SEO-friendly applications with minimal configuration. -## References *(optional)* +## References -- https://nextjs.org/docs -- https://nextjs.org/learn -- https://react.dev \ No newline at end of file +- [https://nextjs.org/docs](https://nextjs.org/docs) +- [https://nextjs.org/learn](https://nextjs.org/learn) +- [https://react.dev](https://react.dev) diff --git a/next/README.md b/next/README.md index 3612b7d..a4297af 100644 --- a/next/README.md +++ b/next/README.md @@ -4,16 +4,16 @@ Next patterns, anti-patterns, and best practices from production codebases. ## Articles -- [Introduction to nextjs](./Introduction-to-nextjs.md) -- [Understanding Routing in Next.js](./Understanding-Routing-in-Next.js.md) -- [not found page in next](./not-found-page-in-next.js.md) +- [Introduction to nextjs](./introduction-to-nextjs.md) +- [Routing Mechanism in Next.js](./routing-mechanism-in-nextjs.md) +- [Custom Not Found (404) Pages in Next.js](./custom-not-found-pages-in-nextjs.md) - [File Colocation in Next](./file-colocation-in-next.md) - [Private Folder in Next](./private-folder.md) - [Understanding Layout in Next](./understanding-layout-in-nextjs.md) -- [Understanding Metadata in Next](./understanding-metadata-in-next.md) +- [Using Metadata in Next](./using-metadata-in-next.md) - [Templates file in Next](./templates-file-in-next.md) - [Loading UI in Next](./loading-UI-in-next.md) -- [Understanding Error handling in Next](./understanding-error-handling-in-next.md) +- [Error Handling in Next.js](./error-handling-in-nextjs.md) ## Ideas for Contributions (but not limited to) diff --git a/next/Understanding-Routing-in-Next.js.md b/next/Understanding-Routing-in-Next.js.md deleted file mode 100644 index 12d84c3..0000000 --- a/next/Understanding-Routing-in-Next.js.md +++ /dev/null @@ -1,55 +0,0 @@ -beginner-friendly article on routing in Next.js using the App Router. It covers file-based routing, nested and dynamic routes, route parameters (params), query parameters (searchParams), active links, programmatic navigation, and routing best practices with practical examples. -# understanding routing in next - -> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - - -## The Problem - -What problem does this solve? Why should the reader care? - -Describe the situation a developer is in when they need this knowledge. Make it concrete. - -## The Solution -beginner-friendly article on routing in Next.js using the App Router. It covers file-based routing, nested and dynamic routes, route parameters (params), query parameters (searchParams), active links, programmatic navigation, and routing best practices with practical examples. -Your main content. Explain the pattern, technique, or approach. - -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. -``` - -If you're demonstrating an improvement, show **before** and **after**: - -```tsx -// Before -``` - -```tsx -// After -``` - -## Tradeoffs - -No solution is free. Be honest about the costs: - -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... - -## Key Takeaways - -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" - -## References *(optional)* - -- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/custom-not-found-pages-in-nextjs.md b/next/custom-not-found-pages-in-nextjs.md new file mode 100644 index 0000000..2c5447d --- /dev/null +++ b/next/custom-not-found-pages-in-nextjs.md @@ -0,0 +1,184 @@ +# Custom Not Found (404) Pages in Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + +## The Problem + +Users don't always navigate to valid pages. They might: + +- Enter an incorrect URL. +- Click an outdated bookmark. +- Follow a broken link from another website. +- Request a resource that no longer exists. + +In a traditional React application, you typically configure a catch-all (`*`) route in React Router to display a custom 404 page. + +In Next.js, this is handled differently. The framework automatically detects unknown routes and renders a **404 Not Found** page. While the default page works, most applications need a custom experience that matches their branding and helps users navigate back to useful content. + +## The Solution + +The Next.js App Router provides built-in support for custom **404 Not Found** pages. You can: + +- Create a global `not-found.tsx` page. +- Display a custom 404 page for specific route segments. +- Programmatically show a 404 page using the `notFound()` function when requested data doesn't exist. +- This article applies to the Next.js App Router (app/), not the Pages Router (pages/). + +### Global Not Found Page + +Create a not-found.tsx file inside the app directory to define a custom global 404 page. + +``` +app/ +├── layout.tsx +├── page.tsx +└── not-found.tsx +``` + +```tsx +// app/not-found.tsx + +import Link from "next/link"; + +export default function NotFound() { + return ( +
+

404

+ +

+ Sorry, the page you're looking for doesn't exist. +

+ + + Go back home + +
+ ); +} +``` + +Whenever a user visits a route that doesn't exist, Next.js automatically renders this page. + +### Handling Missing Resources with notFound() + +Sometimes the route exists, but the requested resource does not. + +For example: + +- `/blog/nextjs-routing` → exists ✅ +- `/blog/random-post` → does not exist ❌ + +Instead of showing an error or blank page, you can render the 404 page by calling `notFound()`. + +```tsx +// app/blog/[slug]/page.tsx + +import { notFound } from "next/navigation"; + +export default async function BlogPost({ params }) { + const post = await getPost(params.slug); + + if (!post) { + notFound(); + } + + return
{post.title}
; +} +``` + +Calling notFound() throws a special Next.js error that immediately stops rendering the current page and displays the nearest not-found.tsx, if post does not exist. + +### Route-Specific Not Found Pages + +In larger applications, different sections may require their own customized 404 experience. + +For example: + +``` +app/ +├── dashboard/ +│ ├── page.tsx +│ └── not-found.tsx +├── blog/ +│ ├── page.tsx +│ └── not-found.tsx +└── not-found.tsx +``` + +If `notFound()` is called inside the `dashboard` route, Next.js searches for the closest not-found.tsx in the current route segment. If none exists, it falls back to the global app/not-found.tsx: + +``` +app/dashboard/not-found.tsx +``` + +instead of the global one. + +This allows different parts of your application to have customized error messages and navigation. + +Example: + +```tsx +// app/dashboard/not-found.tsx + +import Link from "next/link"; + +export default function DashboardNotFound() { + return ( +
+

Dashboard page not found

+ + Return to Dashboard +
+ ); +} +``` + +### Why Use `notFound()` Instead of Returning JSX? + +#### Before + +```tsx +if (!user) { + return

User not found

; +} +``` + +The URL still returns a successful page (HTTP 200), which isn't ideal for SEO or APIs. + +#### After + +```tsx +import { notFound } from "next/navigation"; + +if (!user) { + notFound(); +} +``` + +Next.js returns the correct **404 HTTP status** while displaying your custom 404 page. + +This improves: + +- SEO +- User experience +- Search engine indexing +- Proper HTTP semantics + +## Tradeoffs + +- **When this shines:** Building production applications where users may request invalid routes or missing resources. +- **When to avoid it:** Don't use `notFound()` for permission or authentication errors. Those should return an authorization page or redirect users to sign in. +- **What you give up:** Calling `notFound()` immediately stops rendering the current page, so no additional code after it will execute. + +## Key Takeaways + +- Next.js automatically provides a 404 page for routes that don't exist. +- Create `app/not-found.tsx` to customize the global 404 page. +- Use `notFound()` from `next/navigation` when requested data cannot be found. +- Route segments can have their own `not-found.tsx` files for customized experiences. +- Using `notFound()` returns the proper HTTP 404 status, improving SEO and user experience. + +## References + +- [api-reference/file-conventions/not-found](https://nextjs.org/docs/app/api-reference/file-conventions/not-found) +- [api-reference/functions/not-found](https://nextjs.org/docs/app/api-reference/functions/not-found) diff --git a/next/error-handling-in-nextjs.md b/next/error-handling-in-nextjs.md new file mode 100644 index 0000000..684646c --- /dev/null +++ b/next/error-handling-in-nextjs.md @@ -0,0 +1,292 @@ +# Error Handling in Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + +## The Problem + +Applications don't always work as expected. + +A network request may fail, a database query may throw an exception, a component may crash because of unexpected data, or a third-party service may become unavailable. + +Without proper error handling: + +- Users see a blank page or an unhelpful browser error. +- A single broken component can crash an entire page. +- Developers have little information for debugging. +- Users cannot recover without manually refreshing the page. + +In traditional React applications, developers typically create **Error Boundaries** manually to catch rendering errors. While this works, it requires extra configuration and careful placement throughout the application. + +Next.js simplifies this process by providing **file-based error handling**. By creating special files such as `error.tsx` and `global-error.tsx`, you can display friendly error pages, isolate failures to specific route segments, and even allow users to recover without leaving the page. + +## The Solution + +The App Router provides built-in support for handling errors at different levels of your application. + +There are three primary ways to handle errors: + +- Recovering from route errors using `error.tsx` +- Handling errors in nested routes +- Handling application-wide failures with `global-error.tsx` + +### Recovering from Errors + +To handle errors for a specific route segment, create an `error.tsx` file inside that route. + +``` +app +│── dashboard +│ ├── page.tsx +│ ├── error.tsx +│ └── loading.tsx +``` + +When an error occurs inside `dashboard/page.tsx` or any of its child components, Next.js automatically renders `error.tsx` instead of crashing the entire application. + +#### Example + +```tsx +// app/dashboard/error.tsx + +"use client"; + +export default function Error({ + error, + reset, +}: { + error: Error; + reset: () => void; +}) { + return ( +
+

Something went wrong!

+ +

{error.message}

+ + +
+ ); +} +``` + +#### Why `"use client"`? + +Error components must be **Client Components** because they: + +- Receive the `error` object +- Use the `reset()` function +- Handle user interactions like button clicks + +Without `"use client"`, the component cannot access these features. + +--- + +#### The `error` object + +The `error` parameter contains information about the failure. + +```tsx +console.log(error.message); +``` + +Example output: + +``` +Failed to fetch data +``` + +During development, the error contains the full stack trace. + +In production, Next.js intentionally hides sensitive details to improve security. + + + +#### Recovering with `reset()` + +One of the best features of `error.tsx` is the `reset()` function. + +Instead of forcing users to reload the browser, `reset()` attempts to re-render the failed route. + +```tsx + +``` + +This is useful for temporary problems such as: + +- Network failures +- API timeouts +- Temporary server issues + +--- + +### Handling Errors in Nested Routes + +Error boundaries are **nested**. + +Each `error.tsx` only catches errors inside its own route segment and child segments. + +Example folder structure: + +``` +app +│── dashboard +│ ├── error.tsx +│ ├── page.tsx +│ └── settings +│ ├── page.tsx +│ └── error.tsx +``` + +Here: + +- `dashboard/error.tsx` handles errors inside the dashboard. +- `settings/error.tsx` handles only errors inside the settings page. + +If an error occurs in: + +``` +app/dashboard/settings/page.tsx +``` + +Next.js first looks for: + +``` +settings/error.tsx +``` + +If none exists, it bubbles up to: + +``` +dashboard/error.tsx +``` + +This allows different parts of your application to display customized error UIs. + +--- + +#### Example + +``` +Dashboard +├── Analytics +├── Users +└── Settings +``` + +If the Settings page crashes, only the Settings section displays its error screen. + +The rest of the Dashboard continues working normally. + +This improves the user experience because one broken feature does not take down the entire application. + +--- + +### Handling Global Errors + +Some errors happen outside individual routes. + +For example: + +- The root layout crashes. +- The HTML document cannot render. +- A shared provider throws an exception. +- An application-wide component fails. + +For these cases, create a `global-error.tsx` file. + +``` +app +│── global-error.tsx +│── layout.tsx +│── page.tsx +``` + +Unlike `error.tsx`, this file replaces the **entire application**. + +--- + +#### Example + +```tsx +// app/global-error.tsx + +"use client"; + +export default function GlobalError({ + error, + reset, +}: { + error: Error; + reset: () => void; +}) { + return ( + + +

Application Error

+ +

{error.message}

+ + + + + ); +} +``` + +Notice that the component returns both: + +```tsx + + ... + +``` + +Since this component replaces the entire application, it must render the root HTML elements. + +--- + +### Throwing an Error + +Errors can be thrown manually. + +```tsx +export default async function Dashboard() { + throw new Error("Failed to load dashboard"); + + return
Dashboard
; +} +``` + +Next.js automatically displays the nearest `error.tsx`. + +### Best Practices + +- Keep error messages simple and user-friendly. +- Log errors to monitoring services like Sentry or LogRocket for debugging. +- Use `reset()` for recoverable errors such as failed network requests. +- Create nested `error.tsx` files for independent sections of large applications. +- Reserve `global-error.tsx` for failures that affect the entire application. +- Never expose sensitive server details or stack traces to users in production. + +## Tradeoffs + +Consider the following: + +- **When this shines:** Large applications with multiple route segments. Applications that depend on APIs or databases. Dashboards and admin panels where isolated failures improve user experience. Production applications that require graceful error recovery. + +- **When to avoid it:** Very small applications where a single error boundary is sufficient. Components that can safely handle errors with local conditional rendering instead of throwing exceptions. + +- **What you give up:** Additional files (`error.tsx`, `global-error.tsx`) to maintain.Errors in event handlers (such as button clicks) are **not** caught by route error boundaries and should be handled using `try...catch`. Developers still need proper logging and monitoring to diagnose production issues. + +## Key Takeaways + +- Next.js provides built-in file-based error handling using `error.tsx` and `global-error.tsx`. +- `error.tsx` catches errors for a route segment and its children without crashing the rest of the application. +- Use the `reset()` function to let users retry rendering after a recoverable error. +- Nested routes can have their own error boundaries, allowing failures to be isolated to specific sections. +- Use `global-error.tsx` to handle application-wide failures that affect the root layout or entire app. + +## References + +- [https://nextjs.org/docs/app/building-your-application/routing/error-handling](https://nextjs.org/docs/app/building-your-application/routing/error-handling) +- [https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary](https://react.dev/reference/react/Component#catching-rendering-errors-with-an-error-boundary) diff --git a/next/file-colocation-in-next.md b/next/file-colocation-in-next.md index bc93c9f..5512f06 100644 --- a/next/file-colocation-in-next.md +++ b/next/file-colocation-in-next.md @@ -1,55 +1,178 @@ -This PR adds a new beginner-friendly article explaining file colocation in the Next.js App Router. It covers what file colocation is, why it is useful, how it works, practical examples, trade-offs, and best practices. -# Introduction to Next.js +# File Colocation in Next.js > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - ## The Problem -What problem does this solve? Why should the reader care? +As an application grows, organizing files becomes increasingly difficult. In a traditional React project, components, hooks, styles, utilities, and tests are often grouped by file type. + +For example: + +```text +src/ +├── components/ +│ ├── Button.tsx +│ ├── ProductCard.tsx +├── hooks/ +│ ├── useProducts.ts +├── styles/ +│ ├── product.css +├── utils/ +│ ├── formatPrice.ts +└── pages/ + ├── products.tsx +``` + +While this structure works, finding everything related to a single feature can become frustrating. Every time you work on the product page, you may need to jump between several folders. -Describe the situation a developer is in when they need this knowledge. Make it concrete. +As projects become larger, this scattered structure makes development slower and maintenance more difficult. ## The Solution -Your main content. Explain the pattern, technique, or approach. +Next.js App Router introduces **file colocation**, a pattern that allows you to keep files related to a route together. + +Instead of organizing your project by file type, you organize it by **feature** or **route**. + +The App Router only treats specific files as routes or special files, such as: + +- `page.tsx` +- `layout.tsx` +- `loading.tsx` +- `error.tsx` +- `not-found.tsx` +- `route.ts` + +Every other file inside the folder is ignored by the routing system, allowing you to colocate components, hooks, utilities, styles, tests, and other supporting files next to the page that uses them. + +### How File Colocation Works + +Suppose you're building a dashboard. + +Instead of placing every component inside a global `components` folder. Your folder might look like this: + +```text +app/ +└── dashboard/ + ├── page.tsx + ├── layout.tsx + ├── loading.tsx + ├── UserCard.tsx + ├── Sidebar.tsx + ├── useDashboard.ts + ├── dashboard.css + ├── formatDate.ts + └── dashboard.test.tsx +``` + +Only these files become part of Next.js routing: + +- `page.tsx` +- `layout.tsx` +- `loading.tsx` + +The remaining files are simply supporting files that can be imported where needed. ```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. +// app/dashboard/page.tsx + +import UserCard from "./UserCard"; +import Sidebar from "./Sidebar"; + +export default function DashboardPage() { + return ( + <> + + + + ); +} ``` -If you're demonstrating an improvement, show **before** and **after**: +Since `UserCard.tsx` is only used by the dashboard page, keeping it inside the same folder makes the project easier to understand. + +### Colocate Shared vs Route-Specific Files + +A common question is: + +> **Should every component be colocated?** + +Not necessarily. + +#### Colocate files when they belong to one route + +```text +app/ +└── products/ + ├── page.tsx + ├── ProductCard.tsx + └── ProductFilter.tsx +``` + +If `ProductCard` is only used on the products page, keeping it inside the route folder is a great choice. + +#### Move shared files outside the route + +If multiple routes need the same component, place it in a shared folder. + +```text +components/ +├── Button.tsx +├── Navbar.tsx +└── Modal.tsx +``` + +These components can then be imported anywhere in the application. + +A good rule of thumb is: + +- **Used in one route?** Colocate it. +- **Used in multiple routes?** Move it to a shared location. + +### Benefits of File Colocation + +- Easier Navigation: Everything related to a feature is located in one folder, reducing the time spent searching for files. +- Better Maintainability: Developers can quickly understand a feature without exploring unrelated parts of the project. +- Better Scalability: As your application grows, each feature remains self-contained, making it easier to modify or remove. +- Cleaner Imports: Because related files are close together, imports become shorter. ```tsx -// Before +import UserCard from "./UserCard"; +import useDashboard from "./useDashboard"; ``` +instead of + ```tsx -// After +import UserCard from "@/components/dashboard/UserCard"; +import useDashboard from "@/hooks/dashboard/useDashboard"; ``` +### Best Practices + +- Keep route-specific files inside the route folder. +- Extract components to a shared folder only when multiple routes need them. +- Avoid placing every component in a global `components` directory by default. +- Keep helper functions, custom hooks, styles, and tests close to the feature that uses them. +- Don't over-colocate. If a file becomes widely reused, move it to a shared location. + ## Tradeoffs -No solution is free. Be honest about the costs: +File colocation has advantages and limitations. -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... +- **When this shines:** Large applications with many routes where keeping feature-related files together improves maintainability and developer productivity. +- **When to avoid it:** For utilities or UI components shared across many routes. Duplicating shared code in multiple route folders can make maintenance harder. +- **What you give up:** You may end up with more files inside a single route folder, so it's important to keep the folder organized and extract reusable code when appropriate. ## Key Takeaways -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" +- File colocation means keeping route-specific components, hooks, styles, and utilities alongside the route that uses them. +- In the App Router, only special files like `page.tsx`, `layout.tsx`, `loading.tsx`, and `error.tsx` affect routing; other files are ignored by the router. +- Colocation makes features easier to navigate, understand, and maintain. +- Shared components should live in a common directory, while route-specific code should stay with its route. +- Organizing by feature instead of file type helps Next.js applications scale more effectively. -## References *(optional)* +## References -- [Link to docs, talks, or articles that go deeper](https://example.com) +- Next.js App Router documentation: [https://nextjs.org/docs/app](https://nextjs.org/docs/app) +- Project Organization: [https://nextjs.org/docs/app/getting-started/project-structure](https://nextjs.org/docs/app/getting-started/project-structure) +- Routing Fundamentals: [https://nextjs.org/docs/app/building-your-application/routing](https://nextjs.org/docs/app/building-your-application/routing) diff --git a/next/loading-UI-in-next.md b/next/loading-UI-in-next.md index 05c5872..280689a 100644 --- a/next/loading-UI-in-next.md +++ b/next/loading-UI-in-next.md @@ -1,55 +1,190 @@ -This PR adds a new beginner-friendly article explaining how to implement loading UI in the Next.js App Router using the loading.tsx convention. It covers the problem, solution, practical examples, best practices, tradeoffs, and key takeaways to help developers improve the user experience during route navigation and data fetching. -# Introduction to Next.js +# Loading UI in Next.js > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - +# Loading UI in Next.js ## The Problem -What problem does this solve? Why should the reader care? +Modern web applications often fetch data from APIs, databases, or external services before a page can be displayed. Depending on network speed or server response time, users may have to wait several seconds before seeing the page. -Describe the situation a developer is in when they need this knowledge. Make it concrete. +Without a loading state, users are presented with a blank screen or an unresponsive interface, making the application feel slow or broken. -## The Solution +In traditional React applications, developers typically manage loading states manually using `useState`, `useEffect`, and conditional rendering. -Your main content. Explain the pattern, technique, or approach. +```tsx +const [loading, setLoading] = useState(true); + +if (loading) { + return ; +} +``` + +As applications grow, manually managing loading states for every page becomes repetitive and difficult to maintain. + +The Next.js App Router solves this problem with the **`loading.tsx` convention**, allowing you to define loading interfaces for routes without writing extra loading state logic. + +# The Solution + +In the App Router, placing a `loading.tsx` file inside a route folder automatically creates a loading UI for that route. + +Whenever the page is waiting for server-rendered data or asynchronous components to finish rendering, Next.js instantly displays the loading component. + +For example: + +``` +app/ +│ +├── dashboard/ +│ ├── page.tsx +│ └── loading.tsx +``` + +When a user visits `/dashboard`, Next.js behaves like this: + +1. Navigation starts. +2. `loading.tsx` is rendered immediately. +3. `page.tsx` loads in the background. +4. The loading UI is automatically replaced with the completed page. + +No additional state management is required. + +### Creating a Loading UI + +Create a `loading.tsx` file in the route folder. ```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. +// app/dashboard/loading.tsx + +export default function Loading() { + return

Loading dashboard...

; +} ``` -If you're demonstrating an improvement, show **before** and **after**: +Your page can then fetch data normally. ```tsx -// Before +// app/dashboard/page.tsx + +async function getUsers() { + const res = await fetch("https://jsonplaceholder.typicode.com/users"); + + return res.json(); +} + +export default async function DashboardPage() { + const users = await getUsers(); + + return ( +
+

Dashboard

+ + {users.map((user: any) => ( +

{user.name}

+ ))} +
+ ); +} ``` +While `getUsers()` is fetching data, users will automatically see the loading component. + +### Route-Level Loading + +Each route can have its own loading UI. + +``` +app/ +│ +├── dashboard/ +│ ├── loading.tsx +│ └── page.tsx +│ +├── profile/ +│ ├── loading.tsx +│ └── page.tsx +``` + +Visiting `/dashboard` displays the dashboard loading screen. + +Visiting `/profile` displays the profile loading screen. + +Each loading UI is isolated to its own route. + +### Designing Better Loading Screens + +A loading screen doesn't have to be plain text. + +You can display: + +- Skeleton placeholders +- Spinners +- Animated cards +- Placeholder avatars +- Loading tables +- Progress indicators + +Example: + ```tsx -// After +// app/dashboard/loading.tsx + +export default function Loading() { + return ( +
+
+ +
+ +
+ +
+
+ ); +} +``` + +Skeleton loaders provide a better user experience because they preview the page layout while content is loading. + +### How `loading.tsx` Works + +The `loading.tsx` file is automatically wrapped in a React Suspense boundary by Next.js. + +Conceptually, Next.js does something similar to: + +```tsx +}> + + ``` +This means you don't need to manually add a Suspense boundary for route-level loading. Next.js handles it automatically. + +### Best Practices + +- Keep loading screens lightweight so they render immediately. +- Use skeleton loaders instead of generic spinners when possible. +- Make the loading layout resemble the final page to reduce perceived waiting time. +- Avoid fetching data inside `loading.tsx`; it should only display placeholder content. +- Create route-specific loading screens rather than using the same loader everywhere. + ## Tradeoffs -No solution is free. Be honest about the costs: +- **When this shines:** Loading server-rendered pages, Displaying immediate feedback during route navigation, Building applications with streamed content, and Reducing boilerplate by avoiding manual loading state management. -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... +- **When to avoid it:** When loading a small part of a page instead of the entire route. In such cases, use your own `Suspense` boundary around the specific component. For client-side interactions such as submitting forms or handling button clicks, where component-level loading states are more appropriate. +- **What you give up:** `loading.tsx` only applies to route segments, not arbitrary components. It doesn't replace all loading states; you'll still manage loading manually for client-side interactions and mutations. ## Key Takeaways -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" +- `loading.tsx` provides automatic route-level loading UI in the Next.js App Router. +- Next.js displays `loading.tsx` immediately while the corresponding page is rendering or fetching data. +- Every route segment can define its own loading experience by adding a `loading.tsx` file. +- `loading.tsx` is automatically wrapped in a React Suspense boundary. +- Skeleton loaders usually provide a better user experience than simple text or spinner loaders. -## References *(optional)* +## References -- [Link to docs, talks, or articles that go deeper](https://example.com) +- [Next.js App Router Documentation](https://nextjs.org/docs/app) +- [Next.js Loading UI and Streaming Documentation](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming) +- [React Suspense Documentation](https://react.dev/reference/react/Suspense) diff --git a/next/not-found-page-in-next.js.md b/next/not-found-page-in-next.js.md deleted file mode 100644 index 4940ff7..0000000 --- a/next/not-found-page-in-next.js.md +++ /dev/null @@ -1,55 +0,0 @@ -beginner-friendly article explaining how to create and use custom Not Found (404) pages in the Next.js App Router. It covers creating a global not-found.tsx, handling missing resources with notFound(), route-specific not-found pages, best practices, tradeoffs, and practical code examples. -# Introduction to Next.js - -> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - - -## The Problem - -What problem does this solve? Why should the reader care? - -Describe the situation a developer is in when they need this knowledge. Make it concrete. - -## The Solution - -Your main content. Explain the pattern, technique, or approach. - -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. -``` - -If you're demonstrating an improvement, show **before** and **after**: - -```tsx -// Before -``` - -```tsx -// After -``` - -## Tradeoffs - -No solution is free. Be honest about the costs: - -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... - -## Key Takeaways - -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" - -## References *(optional)* - -- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/private-folder.md b/next/private-folder.md index aa422d1..99432b8 100644 --- a/next/private-folder.md +++ b/next/private-folder.md @@ -1,55 +1,107 @@ -Adds a new beginner-friendly article explaining Private Folders in Next.js, covering what they are, how they work, and how to use a route-specific _lib private folder to organize implementation details without affecting routing -# Introduction to Next.js +# Private Folder in Next.js > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - ## The Problem -What problem does this solve? Why should the reader care? +As your Next.js application grows, the `app` directory can become cluttered with files that are only meant to support a route. These may include: + +- Utility functions +- Data fetching helpers +- Validation schemas +- Constants +- Custom hooks +- Internal components + +Since the App Router creates routes based on the file system, it's natural to wonder whether adding more folders will accidentally create new routes. + +For example, you might organize your project like this: + +```text +app/ +├── dashboard/ +│ ├── page.tsx +│ ├── utils/ +│ ├── hooks/ +│ └── components/ +``` + +Although folders without special files (`page.tsx`, `layout.tsx`, `route.ts`, etc.) don't become routes, Next.js provides an even clearer way to indicate that a folder contains implementation details that should never be treated as part of the routing structure. -Describe the situation a developer is in when they need this knowledge. Make it concrete. +This is where **Private Folders** come in. ## The Solution -Your main content. Explain the pattern, technique, or approach. +A **Private Folder** is a folder whose name begins with an underscore (`_`). -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. +```text +app/ +└── dashboard/ + ├── page.tsx + ├── _lib/ + ├── _components/ + └── _hooks/ ``` -If you're demonstrating an improvement, show **before** and **after**: +Folders prefixed with `_` are ignored by the Next.js routing system. They exist purely for organizing code. -```tsx -// Before +Private folders help communicate that their contents are **internal implementation details** for a specific route or feature. + +### Why use Private Folders? + +Private folders provide several benefits: + +- Keep route-specific code close to the route that uses it. +- Clearly separate implementation details from route segments. +- Prevent accidental route creation. +- Improve project organization as applications grow. +- Make it easier for other developers to understand which files are intended for reuse and which are local to a feature. + +### Example + +Suppose you have a dashboard page that needs helper functions and validation logic. + +```text +app/ +└── dashboard/ + ├── page.tsx + ├── _lib/ + │ ├── fetch-users.ts + │ └── format-date.ts + └── _components/ + └── UserTable.tsx ``` +You can import files normally: + ```tsx -// After +import { fetchUsers } from "./_lib/fetch-users"; +import { UserTable } from "./_components/UserTable"; + +export default async function DashboardPage() { + const users = await fetchUsers(); + + return ; +} ``` -## Tradeoffs +Even though `_lib` and `_components` are inside the `app` directory, they **do not become routes**. -No solution is free. Be honest about the costs: +## Tradeoffs -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... +- **When this shines:** Large applications where each route has its own helpers, components, hooks, or business logic. +- **When to avoid it:** Very small projects where adding many folders creates unnecessary complexity. +- **What you give up:** Route-specific code becomes less reusable. If multiple routes need the same utilities, move them to a shared location like `lib/` or `components/` instead of duplicating them in multiple private folders. ## Key Takeaways -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" +- A **Private Folder** is any folder whose name starts with an underscore (`_`). +- Private folders are ignored by the Next.js routing system and never become routes. +- Use folders like `_lib`, `_components`, and `_hooks` to organize route-specific implementation details. +- Keeping implementation code close to the route improves maintainability and project structure. +- Shared code should live outside private folders in common directories such as `lib/` or `components/`. -## References *(optional)* +## References -- [Link to docs, talks, or articles that go deeper](https://example.com) +- [app/building-your-application/routing/colocation](https://nextjs.org/docs/app/building-your-application/routing/colocation) +- [nextjs.org/docs/app](https://nextjs.org/docs/app) diff --git a/next/routing-mechanism-in-nextjs.md b/next/routing-mechanism-in-nextjs.md new file mode 100644 index 0000000..1517a72 --- /dev/null +++ b/next/routing-mechanism-in-nextjs.md @@ -0,0 +1,463 @@ +# Routing Mechanism in Next + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + +## The Problem + +Navigation is one of the core building blocks of every web application. Whether you're building a blog, e-commerce platform, dashboard, or social media application, users need a way to move between pages seamlessly. + +In traditional React applications, developers often have to install and configure third-party routing libraries like React Router. They also need to manually define routes, handle nested layouts, manage dynamic URLs, and implement navigation logic. + +Next.js simplifies all of this by providing a **file-based routing system**. Simply creating folders and files inside the `app` directory automatically generates application routes, making routing faster, more intuitive, and easier to maintain. + +Understanding how routing works in Next.js allows you to: + +- Build scalable applications with clean URL structures. +- Create dynamic pages from database content. +- Share layouts across multiple pages. +- Navigate between pages without full-page reloads. +- Organize large applications more effectively. + +## The Solution + +Next.js uses **file-system routing**, meaning the folder and file structure inside the `app` directory defines your application's routes automatically. + +``` +app/ +├── page.tsx +├── about/ +│ └── page.tsx +├── blog/ +│ └── page.tsx +``` + +Produces: + +``` +/ -> Home +/about -> About +/blog -> Blog +``` + +### Routing + +Every route in the App Router is created by adding a `page.tsx` file inside a folder. + +Example: + +``` +app/ +├── page.tsx +├── about/ +│ └── page.tsx +├── contact/ +│ └── page.tsx +``` + +```tsx +// app/about/page.tsx + +export default function AboutPage() { + return

About Us

; +} +``` + +Visiting `/about` automatically renders the page. + +No route configuration is required. + +### Nested Routes + +Folders can be nested to create nested URLs. + +``` +app/ +└── dashboard/ + ├── page.tsx + └── analytics/ + └── page.tsx +``` + +Generated routes: + +``` +/dashboard +/dashboard/analytics +``` + +```tsx +// app/dashboard/analytics/page.tsx + +export default function AnalyticsPage() { + return

Analytics Dashboard

; +} +``` + +Nested routes help organize large applications naturally. + +### Dynamic Routes + +Sometimes the URL isn't known ahead of time. + +Examples include: + +- Blog posts +- Products +- User profiles + +Dynamic routes are created using square brackets. + +``` +app/ +└── blog/ + └── [slug]/ + └── page.tsx +``` + +URLs: + +``` +/blog/nextjs-routing +/blog/getting-started +/blog/react-hooks +``` + +```tsx +type Props = { + params: Promise<{ + slug: string; + }>; +}; + +export default async function BlogPost({ params }: Props) { + const { slug } = await params; + + return

{slug}

; +} +``` + +`slug` contains the value from the URL. + +### Nested Dynamic Routes + +Dynamic segments can also be nested. + +Example: + +``` +app/ +└── shop/ + └── [category]/ + └── [product]/ + └── page.tsx +``` + +Routes: + +``` +/shop/shoes/nike-air-max +/shop/laptops/macbook-pro +``` + +```tsx +type Props = { + params: Promise<{ + category: string; + product: string; + }>; +}; + +export default async function ProductPage({ params }: Props) { + const { category, product } = await params; + + return ( + <> +

{category}

+

{product}

+ + ); +} +``` + +### catach-all segements + +Sometimes you don't know how many URL segments you'll receive. + +Use `[...]`. + +``` +app/ +└── docs/ + └── [...slug]/ + └── page.tsx +``` + +Examples: + +``` +/docs/react +/docs/react/hooks +/docs/react/hooks/use-effect +``` + +```tsx +type Props = { + params: Promise<{ + slug: string[]; + }>; +}; + +export default async function DocsPage({ params }: Props) { + const { slug } = await params; + + return

{slug.join(" / ")}

; +} +``` + +#### Optional Catch-all + +If the route should also match `/docs`, use: + +``` +[[...slug]] +``` + +This matches: + +``` +/docs +/docs/react +/docs/react/hooks +``` + +### Route Groups + +Sometimes folders are only used for organization and shouldn't appear in the URL. + +Wrap the folder name in parentheses. + +``` +app/ +├── (marketing)/ +│ ├── about/ +│ └── pricing/ +└── (dashboard)/ + └── settings/ +``` + +Generated URLs: + +``` +/about +/pricing +/settings +``` + +Notice `(marketing)` and `(dashboard)` are omitted from the URL. + +Route groups are useful for: + +- Organizing large projects +- Using different layouts +- Separating public and authenticated sections + +### Link Component + +Instead of using HTML `` tags for internal navigation, use Next.js' `Link` component. + +```tsx +import Link from "next/link"; + +export default function Navbar() { + return ( + + ); +} +``` + +Benefits include: + +- Client-side navigation +- Faster page transitions +- Automatic prefetching of linked pages (when links enter the viewport in production) + +### Active Links + +You can determine the current route using `usePathname()`. + +```tsx +"use client"; + +import Link from "next/link"; +import { usePathname } from "next/navigation"; + +export default function Navbar() { + const pathname = usePathname(); + + return ( + + ); +} +``` + +This is commonly used to highlight the active navigation item. + +### Params & Search Params + +#### Route Params + +Dynamic route values come from `params`. + +``` +/blog/nextjs-routing +``` + +```tsx +type Props = { + params: Promise<{ + slug: string; + }>; +}; + +export default async function Page({ params }: Props) { + const { slug } = await params; + + return

{slug}

; +} +``` + +#### Search Params + +Query strings are accessed using `searchParams`. + +``` +/products?category=phones&page=2 +``` + +```tsx +type Props = { + searchParams: Promise<{ + category?: string; + page?: string; + }>; +}; + +export default async function ProductsPage({ searchParams }: Props) { + const { category, page } = await searchParams; + + return ( + <> +

Category: {category}

+

Page: {page}

+ + ); +} +``` + +For Client Components, use the `useSearchParams()` hook. + +### Navigating Programmatically + +Sometimes navigation happens after an action, such as: + +- Form submission +- Login +- Logout +- Creating a resource + +Use the `useRouter()` hook. + +```tsx +"use client"; + +import { useRouter } from "next/navigation"; + +export default function LoginButton() { + const router = useRouter(); + + function handleLogin() { + // authenticate user... + + router.push("/dashboard"); + } + + return ; +} +``` + +Useful router methods include: + +```tsx +router.push("/dashboard"); // Navigate to a new page +router.replace("/login"); // Replace current history entry +router.back(); // Go back +router.forward(); // Go forward +router.refresh(); // Refresh server components +router.prefetch("/dashboard"); // Prefetch a route +``` + +### Before vs After + +#### Before (React Router) + +```tsx +import { BrowserRouter, Routes, Route } from "react-router-dom"; + + + + } /> + } /> + } /> + +; +``` + +Requires manual route configuration. + +#### After (Next.js) + +``` +app/ +├── page.tsx +├── about/ +│ └── page.tsx +└── blog/ + └── [slug]/ + └── page.tsx +``` + +No routing configuration is required—your folder structure defines the routes. + +## Tradeoffs + +No routing solution is perfect. Here are some considerations: + +- **When this shines:** Building modern applications with nested layouts, dynamic routes, server rendering, and a clear project structure. +- **When to avoid it:** If you're working in an existing React project that doesn't use Next.js, introducing Next.js solely for routing may not be practical. +- **What you give up:** Because routing is tied to the file system, you have less flexibility than manually configuring every route, although this convention greatly improves consistency and maintainability for most applications. + +## Key Takeaways + +- Next.js uses a **file-based routing system**, where folders and `page.tsx` files automatically become routes. +- Dynamic routes (`[slug]`), nested routes, and catch-all segments make it easy to build scalable URL structures. +- Route Groups help organize code and apply different layouts without affecting the URL. +- Use the `Link` component for fast client-side navigation and `useRouter()` for programmatic navigation. +- Route parameters (`params`) and query parameters (`searchParams`) allow pages to respond dynamically to the current URL. + +## References + +- [building-your-application/routing](https://nextjs.org/docs/app/building-your-application/routing) +- [api-reference/functions/use-router](https://nextjs.org/docs/app/api-reference/functions/use-router) +- [api-reference/functions/use-pathname](https://nextjs.org/docs/app/api-reference/functions/use-pathname) +- [api-reference/functions/use-search-params](https://nextjs.org/docs/app/api-reference/functions/use-search-params) diff --git a/next/templates-file-in-next.md b/next/templates-file-in-next.md index 0b696e6..7b7437f 100644 --- a/next/templates-file-in-next.md +++ b/next/templates-file-in-next.md @@ -1,55 +1,228 @@ -This PR adds a new beginner-friendly article explaining Template Files (template.tsx) in the Next.js App Router. It covers what templates are, how they differ from layouts, common use cases, tradeoffs, and includes practical code examples. -# Introduction to Next.js +# Templates File Next > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - ## The Problem -What problem does this solve? Why should the reader care? +By default, layouts in the Next.js App Router are **persistent**. Once a layout is mounted, it stays mounted as users navigate between routes that share the same layout. + +This is usually desirable because it preserves UI state, improves performance, and avoids unnecessary re-renders. However, there are situations where you **want part of your UI to reset whenever navigation occurs**. + +For example: + +- A search panel should clear its input whenever the user visits a new page. +- A page transition animation should replay on every navigation. +- A form wizard should start fresh when navigating back to it. +- Component state should be discarded instead of being preserved. + +Using a layout for these scenarios won't work because the layout persists across route changes. -Describe the situation a developer is in when they need this knowledge. Make it concrete. +This is where **template files** become useful. ## The Solution -Your main content. Explain the pattern, technique, or approach. +A **`template.tsx`** (or `template.jsx`) file is a special file in the Next.js App Router that behaves similarly to a layout, but with one important difference: + +> **Templates create a new instance for every navigation.** + +Unlike layouts, templates **do not preserve component state** between page transitions. Whenever the user navigates to another route that uses the same template, Next.js remounts the template and all of its children. + +``` +app/ +├── dashboard/ +│ ├── template.tsx +│ ├── page.tsx +│ ├── analytics/ +│ │ └── page.tsx +│ └── settings/ +│ └── page.tsx +``` + +In this example, navigating between: + +- `/dashboard` +- `/dashboard/analytics` +- `/dashboard/settings` + +will recreate the template every time. + +### Creating a Template + +A template looks almost identical to a layout. ```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. +// app/dashboard/template.tsx + +export default function Template({ children }: { children: React.ReactNode }) { + return
{children}
; +} ``` -If you're demonstrating an improvement, show **before** and **after**: +The key difference is **how Next.js renders it internally**. + +### Layout vs Template + +Although they have similar syntax, they behave differently. + +#### Layout ```tsx -// Before +// app/dashboard/layout.tsx + +export default function Layout({ children }: { children: React.ReactNode }) { + return ( + <> + + {children} + + ); +} ``` +The layout is mounted once and reused during navigation. + +--- + +#### Template + ```tsx -// After +// app/dashboard/template.tsx + +export default function Template({ children }: { children: React.ReactNode }) { + return ( + <> + + {children} + + ); +} ``` -## Tradeoffs +This component is recreated every time navigation occurs. + +### How Templates Work + +Imagine this route structure: + +``` +app/ +└── dashboard/ + ├── template.tsx + ├── analytics/page.tsx + └── settings/page.tsx +``` + +Navigation flow: + +``` +Dashboard Analytics + │ + ▼ +Template mounts + + │ +Navigate + + ▼ +Dashboard Settings + + │ + ▼ +Old Template unmounts -No solution is free. Be honest about the costs: + │ + ▼ +New Template mounts +``` + +Unlike layouts, the template starts from a fresh state after every navigation. + +### When Should You Use Templates? + +Templates are useful when you need components to **restart** whenever the route changes. + +#### Reset Component State + +```tsx +"use client"; + +import { useState } from "react"; + +export default function Template({ children }: { children: React.ReactNode }) { + const [search, setSearch] = useState(""); + + return ( + <> + setSearch(e.target.value)} + placeholder="Search..." + /> + + {children} + + ); +} +``` + +Every navigation recreates the template, clearing the search input automatically. + +#### Restart Animations + +Many animation libraries trigger animations only when a component mounts. + +Using a template ensures animations replay on every page transition. + +```tsx +"use client"; + +export default function Template({ children }: { children: React.ReactNode }) { + return
{children}
; +} +``` + +#### Reset Forms + +Suppose a multi-step form should always begin from step one whenever users revisit it. + +A template provides a fresh instance without manually resetting state. + +### Layout and Template Together + +You can combine both in the same route. + +``` +app/ +└── dashboard/ + ├── layout.tsx + ├── template.tsx + ├── page.tsx + └── settings/ + └── page.tsx +``` + +A common pattern is: + +- **Layout** → persistent UI such as navigation bars, sidebars, or authentication wrappers. +- **Template** → UI that should reset on every navigation, such as forms, search inputs, or animations. + +This lets you preserve global UI while recreating only the parts that need a fresh state. + +## Tradeoffs -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... +- **When this shines:** When you need state, effects, or animations to reset on every navigation. +- **When to avoid it:** For shared UI like headers, navigation, sidebars, or providers that should persist across pages. +- **What you give up:** Templates remount on every navigation, so local state is lost and initialization code runs again, which may introduce additional rendering work. ## Key Takeaways -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" +- `template.tsx` is a special App Router file that behaves like a layout but remounts on every navigation. +- Unlike layouts, templates do **not** preserve component state between route changes. +- Use templates for components that should reset, such as forms, search inputs, or page transition animations. +- Use `layout.tsx` for persistent UI and `template.tsx` for UI that should start fresh on each navigation. +- Layouts and templates can be used together to balance performance with predictable component behavior. -## References *(optional)* +## References -- [Link to docs, talks, or articles that go deeper](https://example.com) +- [https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts) +- [https://nextjs.org/docs/app/api-reference/file-conventions/template](https://nextjs.org/docs/app/api-reference/file-conventions/template) diff --git a/next/understanding-error-handling-in-next.md b/next/understanding-error-handling-in-next.md deleted file mode 100644 index 1410fea..0000000 --- a/next/understanding-error-handling-in-next.md +++ /dev/null @@ -1,55 +0,0 @@ -This PR adds a new beginner-friendly article, "Understanding Error Handling in Next.js", covering how to handle errors using the App Router. It explains route-level error boundaries with error.tsx, recovering from errors using reset(), handling errors in nested routes, global error handling with global-error.tsx, best practices, tradeoffs, and practical code examples. -# Introduction to Next.js - -> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - - -## The Problem - -What problem does this solve? Why should the reader care? - -Describe the situation a developer is in when they need this knowledge. Make it concrete. - -## The Solution - -Your main content. Explain the pattern, technique, or approach. - -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. -``` - -If you're demonstrating an improvement, show **before** and **after**: - -```tsx -// Before -``` - -```tsx -// After -``` - -## Tradeoffs - -No solution is free. Be honest about the costs: - -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... - -## Key Takeaways - -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" - -## References *(optional)* - -- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/understanding-layout-in-nextjs.md b/next/understanding-layout-in-nextjs.md index 44523dd..6f69386 100644 --- a/next/understanding-layout-in-nextjs.md +++ b/next/understanding-layout-in-nextjs.md @@ -1,55 +1,298 @@ -add the Understanding Layouts in Next.js article with a more comprehensive explanation of layouts in the App Router. This includes improved examples of root, nested, and multiple root layouts, before-and-after code comparisons, tradeoffs, key takeaways, and updated references to the official Next.js documentation. -# Introduction to Next.js +# Understanding Layouts in Next.js > **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - ## The Problem -What problem does this solve? Why should the reader care? +Most web applications share common UI elements across multiple pages, such as: + +- Navigation bars +- Sidebars +- Headers +- Footers +- Authentication wrappers +- Dashboard shells + +Without layouts, you would have to duplicate these components on every page. This leads to repetitive code, inconsistent UI, and unnecessary re-rendering when users navigate between pages. -Describe the situation a developer is in when they need this knowledge. Make it concrete. +Traditional React applications often solve this by wrapping routes in shared components or manually composing layouts. While this works, it becomes harder to maintain as the application grows. + +Next.js provides **Layouts** to solve this problem. Layouts allow you to define shared UI once and reuse it across multiple pages while preserving state during navigation. ## The Solution -Your main content. Explain the pattern, technique, or approach. +A **Layout** is a React component that wraps one or more pages. + +Unlike normal components, layouts are **persistent**. When navigating between pages that share the same layout, Next.js keeps the layout mounted instead of recreating it. This improves performance and preserves client-side state such as: + +- Sidebar expansion +- Scroll position +- Search input values +- Theme settings +- Navigation menus + +Layouts are created using a special `layout.tsx` (or `layout.jsx`) file inside the **App Router**. + +### Root Layout + +Every App Router application must have a **Root Layout**. + +It is located at: + +```text +app/ + ├── layout.tsx + ├── page.tsx +``` + +The Root Layout is required because it defines the HTML document structure for your application. + +Example: ```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. +// app/layout.tsx + +import "./globals.css"; + +export default function RootLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( + + {children} + + ); +} +``` + +The Root Layout is the perfect place for: + +- Global CSS +- Theme providers +- Authentication providers +- Context providers +- Fonts +- Metadata +- Navigation that should appear on every page + +For example: + +```text +app/ + ├── layout.tsx + ├── page.tsx + ├── about/ + │ └── page.tsx + └── contact/ + └── page.tsx +``` + +The rendered UI becomes: + +```text + + + Root Layout + Home / About / Contact + + ``` -If you're demonstrating an improvement, show **before** and **after**: +Every page automatically shares the Root Layout. + +### Nested Layouts + +Large applications often have sections that need their own layout. + +For example: + +- Dashboard +- Admin panel +- Documentation +- User settings + +Instead of wrapping every page manually, you can create another `layout.tsx` inside a route segment. + +Example folder structure: + +```text +app/ +├── layout.tsx +├── page.tsx +├── dashboard/ +│ ├── layout.tsx +│ ├── page.tsx +│ ├── analytics/ +│ │ └── page.tsx +│ └── settings/ +│ └── page.tsx +``` + +Dashboard layout: ```tsx -// Before +// app/dashboard/layout.tsx + +export default function DashboardLayout({ + children, +}: { + children: React.ReactNode; +}) { + return ( +
+ + +
{children}
+
+ ); +} ``` +Now every page inside the `dashboard` folder automatically receives the sidebar. + +Rendering hierarchy: + +```text +Root Layout + └── Dashboard Layout + ├── Dashboard Page + ├── Analytics Page + └── Settings Page +``` + +This keeps dashboard-specific UI isolated from the rest of the application. + +### Multiple Root Layouts + +Sometimes different parts of your application require completely different root layouts. + +Examples include: + +- Marketing website +- Authentication pages +- Admin dashboard +- Customer portal + +Next.js supports this using **Route Groups**. + +Example: + +```text +app/ +├── (marketing)/ +│ ├── layout.tsx +│ ├── page.tsx +│ └── pricing/ +│ └── page.tsx +│ +├── (dashboard)/ +│ ├── layout.tsx +│ ├── dashboard/ +│ │ └── page.tsx +│ └── settings/ +│ └── page.tsx +│ +└── globals.css +``` + +The folders inside parentheses **do not appear in the URL**. + +URLs remain: + +```text +/ +/pricing +/dashboard +/settings +``` + +But each section uses its own layout. + +Marketing pages may have: + +- Landing page navigation +- Public footer +- Hero sections + +Dashboard pages may have: + +- Sidebar +- User profile +- Notifications +- Admin navigation + +This separation keeps each part of the application clean and maintainable. + +### Layout Composition + +Layouts are composed automatically by Next.js. + +For a route like: + +```text +/dashboard/settings +``` + +Next.js renders: + +```text +Root Layout + ↓ +Dashboard Layout + ↓ +Settings Page +``` + +Each layout wraps the one below it, creating a tree of shared UI. + +Without layouts, every page repeats the same structure. + ```tsx -// After +export default function Dashboard() { + return ( + <> + + + +
Dashboard Content
+ + ); +} ``` -## Tradeoffs +```tsx +export default function Settings() { + return ( + <> + + -No solution is free. Be honest about the costs: +
Settings Content
+ + ); +} +``` + +This duplicates UI across pages. The layout handles the shared UI, while each page focuses only on its own content. + +## Tradeoffs -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... +- **When this shines:** Large applications with shared UI, dashboards, admin panels, blogs, and documentation websites. +- **When to avoid it:** Very small applications where only one or two pages exist and shared UI is minimal. +- **What you give up:** Because layouts persist across navigation, you cannot rely on them remounting when changing pages. If a component must reset on every navigation, it belongs in the page rather than the layout. ## Key Takeaways -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" +- Every App Router project must have a **Root Layout** (`app/layout.tsx`). +- Layouts provide shared UI that persists across page navigation. +- Nested layouts allow different sections of an application to have their own shared interface. +- Route Groups let you create multiple root layouts without affecting the URL structure. +- Keeping shared UI in layouts reduces duplication, improves maintainability, and provides a better navigation experience. -## References *(optional)* +## References -- [Link to docs, talks, or articles that go deeper](https://example.com) +- [/building-your-application/routing/pages-and-layouts](https://nextjs.org/docs/app/building-your-application/routing/pages-and-layouts) +- [/api-reference/file-conventions/layout](https://nextjs.org/docs/app/api-reference/file-conventions/layout) +- [/building-your-application/routing/route-groups](https://nextjs.org/docs/app/building-your-application/routing/route-groups) diff --git a/next/understanding-metadata-in-next.md b/next/understanding-metadata-in-next.md deleted file mode 100644 index 4b15db7..0000000 --- a/next/understanding-metadata-in-next.md +++ /dev/null @@ -1,55 +0,0 @@ -This PR adds a beginner-friendly article explaining the Next.js Metadata API, including static and dynamic metadata, routing metadata, title templates, and Open Graph metadata with practical examples and best practices. -# Introduction to Next.js - -> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) - - - -## The Problem - -What problem does this solve? Why should the reader care? - -Describe the situation a developer is in when they need this knowledge. Make it concrete. - -## The Solution - -Your main content. Explain the pattern, technique, or approach. - -```tsx -// Keep code examples focused and production-oriented. -// Show the relevant part, not the whole app. -``` - -If you're demonstrating an improvement, show **before** and **after**: - -```tsx -// Before -``` - -```tsx -// After -``` - -## Tradeoffs - -No solution is free. Be honest about the costs: - -- **When this shines:** ... -- **When to avoid it:** ... -- **What you give up:** ... - -## Key Takeaways - -- 3–5 bullet points the reader should remember -- Each should stand on its own -- Think: "what would I tell a teammate in 30 seconds?" - -## References *(optional)* - -- [Link to docs, talks, or articles that go deeper](https://example.com) diff --git a/next/using-metadata-in-next.md b/next/using-metadata-in-next.md new file mode 100644 index 0000000..dfe7ce3 --- /dev/null +++ b/next/using-metadata-in-next.md @@ -0,0 +1,239 @@ +# Using Metadata in Next.js + +> **Topic:** Next.js · **Level:** Beginner · **Author:** [@geliettech](https://github.com/geliettech) + +## The Problem + +Every web page contains more than just the visible content. Search engines, browsers, and social media platforms rely on **metadata** to understand what a page is about. + +Without proper metadata, your application may have: + +- Generic browser tab titles like **Next App**. +- Poor search engine optimization (SEO). +- Unattractive previews when links are shared on social media. +- Missing page descriptions and icons. +- Difficulty identifying pages in browser history and bookmarks. + +In traditional React applications, developers usually manage metadata using libraries such as `react-helmet`. In Next.js App Router, metadata management is built into the framework, making it easier to define SEO-related information for every page. + +## The Solution + +Next.js provides a **Metadata API** that lets you define metadata at the layout or page level. + +Metadata can be: + +- **Static** – defined using the exported `metadata` object. +- **Dynamic** – generated at request time using `generateMetadata()`. + +Metadata automatically renders appropriate HTML tags inside the document's ``. + +### Routing Metadata + +Metadata follows the same hierarchy as the App Router. + +You can define metadata in: + +- `app/layout.tsx` (applies to every page) +- Nested layouts (applies only to routes within that layout) +- Individual pages (overrides parent metadata) + +For example: + +``` +app/ +├── layout.tsx +├── page.tsx +├── about/ +│ └── page.tsx +└── dashboard/ + ├── layout.tsx + ├── page.tsx + └── settings/ + └── page.tsx +``` + +- `app/layout.tsx` provides metadata shared across the entire application. +- `dashboard/layout.tsx` overrides metadata only for dashboard pages. +- `dashboard/settings/page.tsx` can further customize its own metadata. + +Metadata is **merged** from parent layouts down to child pages. + +### Title Metadata + +This is simplest metadata you can define is the page title. + +```tsx +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Home", +}; + +export default function HomePage() { + return

Home Page

; +} +``` + +This generates: + +```html +Home +``` + +### Adding a Description + +```tsx +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "About", + description: "Learn more about our company.", +}; + +export default function AboutPage() { + return

About Us

; +} +``` + +Generated HTML: + +```html +About + +``` + +--- + +### Default Title Template + +Instead of repeating your website name on every page, define a template in the root layout. + +```tsx +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: { + default: "My Store", + template: "%s | My Store", + }, +}; +``` + +Now a page can simply define: + +```tsx +export const metadata = { + title: "Products", +}; +``` + +The browser title becomes: + +``` +Products | My Store +``` + +If a page doesn't specify a title, the default becomes: + +``` +My Store +``` + +--- + +### Dynamic Metadata + +Sometimes metadata depends on fetched data. + +For example, an e-commerce product page should display the product's name in the browser title. + +Instead of using a static object, export `generateMetadata()`. + +```tsx +import type { Metadata } from "next"; + +type Props = { + params: Promise<{ id: string }>; +}; + +export async function generateMetadata({ params }: Props): Promise { + const { id } = await params; + + const product = await fetch(`https://api.example.com/products/${id}`).then( + (res) => res.json(), + ); + + return { + title: product.name, + description: product.description, + }; +} + +export default function ProductPage() { + return

Product Page

; +} +``` + +Every product page now has unique metadata generated from its data. + +### Other Common Metadata + +Next.js supports much more than just titles. + +```tsx +import type { Metadata } from "next"; + +export const metadata: Metadata = { + title: "Blog", + description: "Latest articles", + + keywords: ["Next.js", "React", "JavaScript"], + + authors: [ + { + name: "Geliet Tech", + }, + ], + + icons: { + icon: "/favicon.ico", + }, + + robots: { + index: true, + follow: true, + }, +}; +``` + +You can also configure: + +- Open Graph metadata for Facebook and LinkedIn. +- Twitter Cards. +- Canonical URLs. +- Verification tags. +- Theme colors. +- Apple web app settings. +- Alternate languages. +- Manifest files. + +These help improve SEO and how your pages appear when shared online. + +## Tradeoffs + +- **When this shines:** Building applications that need good SEO, social sharing, or meaningful browser titles. +- **When to avoid it:** Almost never. Metadata is lightweight and should be used for nearly every page. +- **What you give up:** Dynamic metadata may introduce additional data fetching, so avoid unnecessary requests if the information is already available. + +## Key Takeaways + +- Next.js includes a built-in Metadata API, so you don't need libraries like `react-helmet`. +- Metadata can be defined globally in layouts or locally in individual pages. +- Child routes inherit and can override metadata from parent layouts. +- Use `metadata` for static values and `generateMetadata()` for dynamic, data-driven pages. +- Well-defined metadata improves SEO, browser usability, and link previews. + +## References + +- [https://nextjs.org/docs/app/api-reference/functions/generate-metadata](https://nextjs.org/docs/app/api-reference/functions/generate-metadata) +- [https://nextjs.org/docs/app/building-your-application/optimizing/metadata](https://nextjs.org/docs/app/building-your-application/optimizing/metadata)