I'm only 7 minutes into this and felt the need to leave a message. This is fantastically explained. I've watched many other videos but non have explained it as well as you. Thank you.
I've searched for the proper channel for a long time, and I must admit that became in love with your communiation style almost instantly. This is where I learn the best. Thank you for doing this!
Struggled about how to share state across the whole app with server components, and now you made it so clear and easy through that small example project. That was literally you answering my question exactly as I needed to! Thank you Hamed that was amazing explanation 👌🙏
Please, make a video about internazionalization with server and clients components. And cover how to pass in corrrect way translations and intl usage if yoy want create an array of translations. Its inportant topic
This video is awesome, it should included directly into the nextjs app router documentation! Seriously, it was two days i was trying to understand these differences coming from 4 years of page directory structure and your video is extremely clear. I'm gonna see also all the other videos you published!
Thank u so much ! Next.js documentation says next: "use client" is used to declare a boundary between a Server and Client Component modules. This means that by defining a "use client" in a file, all other modules imported into it, including child components, are considered part of the client bundle - and will be rendered by React on the client. I Read this and thought that anything passed to a client component became client component. Even though it says: all other modules IMPORTED into it, including child components..... Yeah, my bad :( I re-search the whole internet about 'how to create a theme provider in next.js so that the app remains rendering on the server side' and found nothing. And you explained this perfectly. Thank u, i appreciate this:)
I finally understood and the restlessness inside me disappeared. I couldn't help but get angry at myself, comparing me, who was hectic, and you, who was relaxed while coding.
thank you very much for the information, but I'm curious about a few things if we have fetching on the client and server side, how to secure the paths there is little information on this subject and the second thing is whether using the backend in Java makes any difference in this puzzle?
I have a couple of videos where I show how to protect your server vs client components/pages in NextJs 13 using the `next-auth` package as well as Clerk.
I stumbled across your channel this week and have started binge watching everything. This is by far the best NextJS content on RU-vid. I started using next properly a few months ago and having come from a React/Node(Express) mind set, I found it tricky to make a comfortable transition into NextJS. So hard to leave behind the routes/controllers/middleware folder structures 😭 I haven't found any channel that talks about transitioning your mindset from Node/Express to NextJS (maybe because most devs are still trying to figure it out!) but your way of explaining things are so clean and refreshing to listen to, I have managed to see NextJS from a different viewpoint and am starting to totally get it and feel more confident with it. I feel like my imposter syndrome is now cured! Looking forward to seeing more content in the future 😎 EDIT: oh and I finally understand how to use next/image to display my images as I want them!
Brilliant!!! Thank you for this great explanation for such a confusing matter for me! Btw the whole video I'm imagining you're a scientist explaining things in a lab because of that white shirt lol! I suggest you embrace it, it helped me concentrate and really take in what you're explaining, seriously! 🤣🙏
This is an excellent video! Very clear and well explained with perfect examples. Thank you Hamed, another great piece of work from you - really helpful. You have the ability to explain complex things in a simple to understand way. Appreciated by me and many others, I'm sure.
Great explanation thank you! What if the page is about current user information like a profile page. isn't every bit of information on the page listed is somehow becomes client component just because we need to get user name from URL and fetch data from API to show related info on the page?
I appreciate your feedback Usama. In this particular video Typescript wouldn't have made much of a difference. I have a couple of videos using Typescript in NextJs 13, also with prisma: ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-XmWGqi0pskU.html ru-vid.com/video/%D0%B2%D0%B8%D0%B4%D0%B5%D0%BE-8e35eo447Zw.html
Hi, first of all, great video. I have a question regarding client-side components. In the early stage of the video, you mentioned that every component inside the client component becomes the client component. However, later on, for instance, with the ThemeProvider, we're creating a child component and using the children there to use the server component inside the client component. So, how are these terms different from one another? You mentioned in the video that if we import the server component inside the client component, then it becomes the client component, but if we use it like "children," then it will not. Can you explain the reason behind this? Thanks.
The difference is when you import vs pass a server component as props (children). When you import, you pass the server-client boundary marked by `use client` directive and therefor the server component is treated as a client component as far as your bundler is concerned. When passed as props this is not the case.
Hi Hamed, I follow almost the same step, the only difference is instead of importing themeprovider in the provider component like you do, I have imported use stete and use effect. My goal is simply to run a normal JSX element between the opening and closing bracket of the child component in the parent component. So, when I applied the child component in a parent component, I got an error message saying : 'Objects are not valid as a react child(found object with keys children). If you meant to render a collection of children, you an array instead.' Also, if the opening and closing brackets of the child component is empty, I have an error message saying : 'property 'children' is missing in type {''} but required in type '{children:any}'. What did I make wrong? thank you!
I have a scenario where I need to use a server component inside a loop of client components. This means a map method is running and returning a server component. How can I achieve this? Also, if I pass a server component as a prop to a client and that server component requires some props to be passed in, and those props are in the client component, how can I accomplish this?
What is the scenario that requires this? You can use server components the same way you'd use any component in a map loop; as far as passing props you can use the URL to keep and pass the state from client to server.
Glad it was helpful. The warnings are for pre-loading css in dev, you don't need to worry about it. To disable prefetching in your `link` components you can pass the `prefetch={false}` prop.
Hey! Thank you for this video. I stumbled upon it because I’m trying to understand how to update data that I rendered using a server component (aka the data was sent to the elements of the page on the server) and that I want to push a new element to that data when the user adds it via a form without doing a full page refresh but I still don’t seem to find/understand how to
If you're using server actions on your form to update the data, you can call the `revalidatePath` function on the server to refresh the data. If you're hitting an API from your form, you can then use the `useTransition` hook and call `router.refresh` inside of it to refresh the page without a full page reload.
Hi, thanks for this very clear explanation, it confirms in an easy to understand way what I took from reading the official documentation. Good job! :) I do have some remaining doubts on overall architecture of my UI. Taking your blog page example and adding my restraints, maybe you could share your thoughts. What if: - my sidebar is collapsible. So it has user action, it needs to show or hide depending on user choice. So I need to wrap it in a client side component that answers to a state - my blog posts sit inside tabs or accordion. I need to wrap my blog content in a client side component because again, content shows or hides depending on user interaction and state - my logo depends on device/window size. I need to access the window object to decide whether I want a mobile or desktop version of the logo. - my footer has a desktop or mobile layout, I need to decide which one to load. Again, I need to access the window object or a 3rd party library that uses hooks - if I added a table to display data I may want to make it sortable or filterable - again content, or presentation of content, will be subject to user interaction - what if I wanted to add a display toggler from say grid to list for my blog posts. I would need to wrap them in a client side layout component that answers to user input and state In the end, everything on my page is subject to some sort of user interaction. I cannot imagine a UI I have built over the last few years that simply loads static content in an isolated manner. How would you address the above? Import server side components for content as children into a client component for presentation for every instance? Would it even make sense to use server components at all for this? Just have the layout on the server side and fill it up with client side components? Then, again, I hardly need the server side at all! For the largest part, when I look at complex UIs I struggle to find instances where I load content which does not need any user interaction or any browser interaction at all. The only useful instance I can imagine is to load placeholder data instantly from server side for SEO purposes and then replace it with the client side component once it's ready. Looking forward to hearing your thoughts :)
Some of the functionalities you mentioned, like different logos and footers, can be done using CSS media queries instead of JS. That said, user interactivity is an inevitable part of any application, and there is nothing wrong with using client components. Server components are not meant to replace client components. You can benefit from your server infrastructure by keeping dependencies on the server rather than shipping more JS to the client, resulting in a faster page load and, hence, a better user experience. You can then sprinkle client components where user interactivity is needed. The App router, built on top of Server components and suspense, also has a better DX. You can fetch data inside your component instead of having to use `getStaticProps` or similar APIs and stream the response to the client. Layouts, suspense, and error boundaries are native and just a file in each segment. The new architecture may only be necessary or proper for some applications. You can choose what works best for your specific application needs.
@@hamedbahram thanks for your reply :) Yes, I was a bit dramatic, just to make a point. :) I am trying to convert an existing UI to best make use of the new tech and find myself at a point where I realise: basically everything is interactive, even a simple thing like a page footer. Data fetching inside components definitely is the most useful feature for my needs, together with streaming UI components which I neeed to look more into. Media queries can go a long way (although you may then load redundant files into your HTML - there is never a perfect solution :)) Thanks for taking the time to post your clarifying thoughts! 😀
Good question! there are different ways to go about this, you can use the `searchParams` in the URL and read it in your server component to fetch data. I'll have a video on this topic coming out next week, so stay tuned.
Although a newer version of next.js have high performance for operations and best facilities. But it have some limitations. For example I can not callback up from client component to server component (Scenario for using intersection observer to trigger a function when an specific img is in view . I mean set src when img in viewport)
Hello Hamed, There's some remarks that you speak about, not being able to put a server component inside a client component(without turning it into a client component), around 4:00, but in your most recent videos you mention that indeed you can do that. Is this something that recently changed?
You can pass a server component to a client component as props or as a children but you cannot import a server component into a client component. Hope this clarifies the confusion.
I have a application where i'm creating static pages for the dynamic routes and there is an add-to-cart button. So the button should be considered a child in server-side components or do I have to accept the server components into the client components as a children? thank you so much
I have a question. I was using framer-motion with this new nextjs version and when ever I use the framer-motion library in a page I have to make the page a client side component. so if I have a site with animations in every page, all of my pages will have to be a client side component. Is this a bad thing ?
It's not bad, but you won't benefit from React server components. Instead of turning the whole page into a client component, try abstracting the animating components into isolated client components and keep your pages as server components.
Anyone else thinking this comes with a considerable development overhead compared to previous versions? FE development is becoming increasingly complicated
It's definitely different from the patterns we've been used to, but once you get over the hump, it actually simplifies the development in my opinion. For example, data fetching doesn't require any extra NextJs specific function like the `getStaticProps` and `getServerSideProps` instead you fetch data right inside your server components. Layouts, loading UI, error boundaries are native in the app router and doesn't require any extra work from the developer, and many more... Once you start building with the new App router you won't go back.
I have a server ui component that conditionally render in Navbar according to the user if its present in cookies or not. It will either display logout button or signin button. My problem is, its not updating ui by clicking signin or logout button ui using server actions even after revalidating paths. I need to manually referesh the page for nabar ui to change. Do you know how can I go about that. Thank you
I'm not sure why that is, I'd have to look at your code to understand what's happening but try exporting the `dynamic` route config and set it to `force-dynamic` and see if that makes a difference.
@@hamedbahram Thanks for the reply man! I did it and it really works, but what if I want to build this UI in a monorepo with server components to share between several Next projects? I would love to see your opinion on this on a vid maybe!
32:00 why is the pre-rendering behavior different when adding the mounted state? Without it, it seems that the component gets pre-rendered on the server using the MoonIcon and there is no second chance on the Client side to re-render this component when resolvedTheme changes, in order to show the SunIcon. Why is it any different after adding the mounted state, i.e., why doesn't the same behavior apply such that "null" is always rendered with no second chance to re-evaluate the output of this component?
I'm not sure if I understand the question correctly. However from a high level, the `resolvedTheme` is not defined on the server since we don't have access to the browser local storage or the user system preferences, therefor we prevent rendering the theme toggle button until mounted on the client using the mounted state. If we render the theme toggle on the server, it may show the wrong theme selected.
@@hamedbahram Ah... I think I understand my confusion now. So the button *would* change to the correct button after the first click, but you are adding the mounted state only to fix the initial button. Thanks!
@@hamedbahram So then my question becomes (assuming we have not yet added the mounted state): when the pre-rended button gets to the Client and the resolvedTheme value changes from undefined (it was undefined on the server) to 'dark', doesn't the entire component re-render?
On the client the value doesn't change from `undefined` to `dark`, it will be initialized to `dark` reading from the user browser local storage or system preferences. `next-themes` runs a script to set the correct attributes on the `html` tag before the rest of you application loads. The mismatch only happens when you're rendering UI that depends on the current theme on the server, and to avoid that we're using the `mounted` state to only render theme dependent UI on the client.
you said we can not import client components in server components , but then you imported ThemeButton component inside header compoenent , which is server compoenet by default.. can you please clear this ... apart from that salute to the way you explain things.. have discover your channel recently and i must say its one of the top channels for learning next js...
You can import client components in server components, but you cannot do the other way around. Meaning you cannot import server components in client components.
Hi, first of all - Great video! You explained beautifully the distinction between server & client components. I'm new to next.js (since yesterday 🙂) and it really sheds some light. I have a question that I hope you can assist with: I have a React CSR app that I'd like to migrate to next.js, mainly for SEO reasons. I'm using the MUI component library, including its theming API, which is executed in the client. I can't figure out a way to use it in my server components... Do you know a trick? Thanks, Oren
Hi Oren! Thanks for your comment, I appreciate it. Unfortunately MUI doesn't support the App router in NextJs 13 yet, it might come in future. But for now you need to wrap third-party component that are meant to run on the client in your own client component using the `use client` directive.
Just a quick question...around 9:05 you mention that when React renders a server component and encounters a client component, it leaves a little slot for it...and once the content reaches the client side, the client components will be rendered and the slots will be filled. But...if you client components are pre-rendered on the server and merely hydrated in the browser...doesn't that mean there shouldn't be any "slots" or "holes" regarding the content sent to the browser from the server? Shouldn't all the html already be generated for them?
There is a difference between React and NextJs in how they render client components. From a React perspective, client components are primarily rendered on the client, so when they are encountered during server renders there would be slots left for them. NextJs on the other hand pre-render client components on the server, so the initial html going to the browser has the client component parts as well.
Not at all. Client components would also pre-render on the server during SSR, you can also pass server components as props or children to client components while remaining server components.
Thank you for purchasing the course, Rehan! I appreciate it. I'm finishing the final edits on the ecommerce project mainly merging Clerk authentication with Swell. The lesson should be up in the following days this week.
@@hamedbahram thank you. Do you use redux? I usually use redux for state management, and redux toolkit query for fetching and caching. Do you think we still need redux for next 13? Thank you.
Well, with React server components you'll fetch data on the server, and use HTTP cache. You can still fetch data client-side using libraries like SWR or ReactQuery that have caching built-in. I'm using React context for global state in the projects. If I were to use a state management solution, I would go for something like Zustand. You can still use Redux but I don't see any particular benefit.
Wow, what an incredible video! Thank you so much ❤️ I have a question: Do you think it's beneficial to utilize React Query for managing server-side state? cuz we can now fetch data using RSC and mutate data with server actions, I'm curious about your thoughts on incorporating React Query or even SWR with Next.js. Thank you once again for this amazing content! ❤️
Thanks for your kind words. SWR or React query are suitable for fetching data on the client. However it's recommended to move your data fetching to your server components server side. You can utilize the NextJs cache to store the result of your data fetching for subsequent requests.
Currently, I have my data fetching logic in redux as i am using createAsyncThunk and i am using useSelector to select a state from my redux store. I have usecase wherein i get a json from backend and by going through the json, I construct my filter section, now any time user updates a filter, i dispatch an action to re-fetch data for table component. I am not able to figure out how to do the same in next.js 13 using server and client components?
There are different ways to do this. You can use URL search parameters to hold your filter state, or you can use context to have your filter state client side and fetch an API endpoint when the filter changes.
@@hamedbahram thanks for the reply☺. I am re-posting my question with more detail. Currently, I am using redux-toolkit and create-react-app to implement a page wherein I have a filter section and a table. filter section is created by reading a json that i receive by hitting '/filters' endpoint. Anytime user change a filter, I dispatch an action to update the filter slice. In my table component, I am accessing the filter slice using selector and as filter slice change, i re-fetch data for table. Coming to the next world. the thing is even if i abstract out the filter logic in a separate file and make it run on server, i want to put in the fetched data in redux store. Now if i will access redux store in the same place where i am fetching data, i will have to make it client side component. Sorry Hamed for shooting a lot of questions at you. Hope to hear back from you.
@@hey............. I think the flow you explain should work, and that yes you would have to turn the component that uses Redux into a client component. I have a video coming out soon where I'd show a similar concept of implenenting search filters.
@@hamedbahramI have a page with many products, I'm fetching products from a database in sever component and sending it as a prop to client component to render on screen. I want to add filters to it. Should I fetch them in client side as I'm not able to use important client side features
@@arjuns.3752 There are different ways to implement this, one way is to use a client component as you mentioned. I'll make a video on this topic soon since it has been brought up a few time :)
it is very confusing and conflicting interests of client component and server components, while saying: "preferably to server components" unless I need onClic interactivity etc... all the time you have interactivity in component... yeah this relationship of interest is very confusing... I already use react for a long time and I still find it very confusing SSR and the next one seems to have come to make it even more confusing....
Coming from a traditional React application which is rendered primarily on the client, the new features in React 18 like server components can be confusing. It's definitely a new way of building React applications. I hope I can introduce some of the new concepts in these tutorials. Let me know if I can help to clarify some of the stuff you find confusing.
@@hamedbahram brother I have a doubt. Kindly give some tips if u ever get some free time. my company uses nextjs for the frontend and python django for backend. Right now for authentication we use jwt tokens .so i use the react use effect and redux toolkit to check the authentication. Is there any other methods u could suggest in a nextjs way
Thanks for your videos, I had a doubt with this video and the previous one... in relation to what you say in the minute 13:00 avoid poisoning using (import "server only") then when I query or add data using prisma I should use this instruction import "server only" // ?????????? import prisma from './prisma'. export async function getProducts() { try { const products = await prisma.product.findMany() console.log("prismaTODODO ", products) return { products } } catch (error) { return { error } } } Greetings Jose Grillo from Venezuela
The `PrismaClient` won't run on the client and it will fail, plus that your `DATABASE_URL` should also be stored as a private env variable, which means the client code doesn't have access to it. So you won't need the `server-only` package in that case. But as a general good practice you can use the `server-only` package anytime you're creating function that are only ever meant to run on the server.