Server and Client Components
In Next.js, it's important to distinguish between server and client components because they operate in different environments with distinct limitations
Server Components
- No Hooks: React hooks like useState, useEffect, or useContext cannot be used in server components because they rely on client-side functionality.
- No Browser APIs: Server components do not have access to browser-specific APIs like window, document, localStorage, or sessionStorage. These APIs only exist in the browser and are not available during server-side rendering (SSR).
- Static Rendering: Server components are rendered on the server before being sent to the client. This makes them ideal for rendering static content or performing server-side logic, such as data fetching.\
Client Components
- Full Access to Hooks: Client components can use all React hooks to manage state, side effects, and context because they run in the browser.
- Access to Browser APIs: Client components have full access to browser APIs, enabling dynamic behavior like showing alerts (window.alert()) or interacting with localStorage.
- User Interaction: These components are responsible for handling user interactions and dynamic content updates in the browser.
In Next.js, understanding the distinction between server and client components is crucial for optimizing performance and ensuring that your application works as expected.
const Ten = () => {
// Server & Client components
// there are no hooks on the server, they only exist on the client
// window.alert() -> this also doesn't work
// localStorage doesn't exist either
return <div></div>;
};
export default Ten;