Next js - Chapter 1 Exercise

Published

Exercise


Absolutely! Here are some **questions and exercises** to help you understand the difference between Server Components and Client Components in Next.js, based on the [Next.js documentation](https://nextjs.org/docs/app/getting-started/server-and-client-components):


---


## **Questions**


1. **What is a Server Component in Next.js? How does it differ from a Client Component?**

2. **How does data fetching work in Server Components compared to Client Components?**

3. **Can you use React hooks like `useEffect` and `useState` in Server Components? Why or why not?**

4. **When would you use a Client Component instead of a Server Component? Provide two use cases.**

5. **What happens when you try to import a Client Component into a Server Component? What about the reverse?**

6. **Which type of component (Server/Client) is best for rendering dynamic data that does not need to interact with the browser directly?**

7. **Describe the performance benefits of using Server Components in a Next.js app.**

8. **How do you mark a file as a Client Component in Next.js?**


---


## **Exercises**


### 1. **Identifying Components**

Given the following snippet, identify which are Server Components and which are Client Components. Explain your reasoning.


```jsx

// app/page.js

export default function Page() {

  return <h1>Hello World</h1>;

}


// app/button.js

'use client';

export default function Button() {

  return <button>Click me</button>;

}

```


---


### 2. **Refactor to Server Component**

Take this Client Component and refactor it to work as a Server Component (if possible). What needs to change?


```jsx

'use client';

import { useState } from 'react';


export default function Counter() {

  const [count, setCount] = useState(0);

  return <button onClick={() => setCount(count + 1)}>{count}</button>;

}

```


---


### 3. **Data Fetching Comparison**

- Create a Server Component that fetches data from an API.

- Create a Client Component that fetches data from the same API using `useEffect`.


Compare and contrast the two approaches.


---


### 4. **Mixing Components**

- Create a page where a Server Component imports a Client Component (such as a button).

- Explain what happens and why Next.js allows this pattern.


---


### 5. **Hook Usage**

- Try using `useEffect` in a Server Component. What happens? Why?


---


## **Bonus Challenge**


- Build a simple Next.js page using both Server and Client Components.  

- Add comments explaining which parts must be Client due to browser interactivity and which can be Server for improved performance.


---


Let me know if you want sample solutions, hints, or further discussion on any of these!