# The Only Library You Need for React / Next.js Image Optimization and File Uploading

## Метаданные

- **Канал:** Lama Dev
- **YouTube:** https://www.youtube.com/watch?v=YP3BL4jIBHM

## Содержание

### [0:00](https://www.youtube.com/watch?v=YP3BL4jIBHM) Segment 1 (00:00 - 05:00)

Hi friends, today I’m gonna talk about one of the most challenging parts of web development when it comes to optimization and user experience. And this part is media. Images and videos on our websites play a crucial role in overall performance, But, I think many developers tend to focus more on optimizing their JavaScript and CSS assets than on their media. They mostly focus on reducing Javascript bundle sizes from 120 kilobytes to 100 or decreasing server response times from 600 milliseconds to 500. But that might not be the most important problem. They open their consoles, see this tiny turtle icon, or analyze their websites on Google’s PaseSpeed Insights, and immediately think that their website is too slow, or their code is terrible. I’m not saying it’s not important, but if you are not using a slow server or your application is terribly designed, you probably don’t need to worry. Let me give you some examples from some of the biggest websites. Let’s visit x. com. There are some slow server response times. And if you analyze the website, you’ll see that the performance is 50%. Youtube is 40%, Reddit is 52%, Yahoo is 55, Udemy 47, Even the mobile version of React’s official website is 63%. But, there is one thing all these websites have in common. They all do a great job with media optimization. Let’s think of it from a regular user's perspective; forget that you are a developer and imagine you want to visit IKEA’s website. And it wasn’t super fast, but I can see all the images and videos immediately. So, as a regular user, if I can see the content fast enough, I mean in a couple of seconds, I don’t expect anything else. But if you open the console or analyze the website, you will see that the performance is not good at all. Or let’s visit Pexels. com. It’s not the fastest opening website but it’s good enough. And after the loading, I can see all the images almost instantly. So, what I’m saying is that some of the web developers often rely too much on these analyzers. If you split your code, fetch data properly, and deploy your application to a reliable server, try to focus on your content and optimize images and videos as much as possible. But it’s not always easy because if your website is not static, if content changes frequently, or if users can upload and display different images and videos like in most web applications, you might have some optimization problems. Let’s talk about the regular image and video HTML tags. I’ll add the source image and video. And of course, the sizes are too big. The image is almost 8, and the video is almost 50 megabytes. Even if I give a different size, here is gonna be the same. Let’s add a width and height. Refresh the page. And they are still the same. Because we're only resizing the frame, not the actual image or video. So what we should do here is, we should create different versions of the image and video for each screen size and use the correct source for each. But again, this is not possible if your content is dynamic or if you have many images. So we have to find a different solution. If you are using Next. js, there is an awesome built-in solution for images. Just replace your image tag with the Next. js Image component and give your width and height. And right now, the file size is smaller. Because the Image component resizes the media according to given dimensions. But, the problem is that this component serves all images directly from the server. Even if you use an external image, it’s gonna store that on the server. And if you use a single server with thousands of images, it’s better to use a CDN. But when using a CDN, you’ll need to write a different loader to display the images.

### [5:00](https://www.youtube.com/watch?v=YP3BL4jIBHM&t=300s) Segment 2 (05:00 - 10:00)

And there is no solution for videos, and it cannot be used in pure React applications. So, for all your projects, you may need a single and reliable solution. This is why I started using ImageKit. ImageKit is not just a media storage solution; it’s a complete media delivery and management platform. You can upload your images and videos. And it has a generous free tier. So you can test it for your next project. When you display images on your website, ImageKit optimizes them in real-time. And, you can modify this compression level. If the user’s network is slow, you can show low-quality images. You can also transform images instantly by just changing the image URL. You can crop, give a shape, and apply other effects. You can write any text. And again, you are just changing the URL to do that. And most importantly, you can use lazy loading placeholders for the best user experience. It’s also possible to hide your images from unauthorized requests. And the best thing is you can use different cloud options together. So even if you store your images in a different storage like AWS or Google Cloud, ImageKit is gonna access them so, you’ll be able to use all these features for those images. Let’s open the documentation and see how to use it. As you can see, you can use it with most of the languages and frameworks. Let’s choose Next. js. We already have our application. I’ll skip here. We are gonna need this library. Let’s install. npm install imagekitio-next After that, I’m gonna open the dashboard and get my public and private keys Let’s pass them to our env file. In the root folder, I’ll create my env file, and paste them here. Right now, I can open my dashboard. There are some default examples, but you can also upload your files here. Of course, I’ll show you how to upload images in your application using ImageKit, but I just wanted to show you how to do that on the dashboard. Let’s open the developer options. As you can see, this is the ImageKitId, which will appear on the image URLs. Let’s copy and paste these keys. And now we are ready to display our images. Firstly, I’m gonna add this Imagekit URL to the Next. js configuration because, by default, Next. js doesn’t allow us to use any external images. After doing that, we’ll be able to display the images using this component. We’ll write here the URL endpoint. And the other details are similar to Next. js Image component; instead of the source, we’ll be using the path. You can directly use this component here, but each time you have to write this endpoint again and again. To prevent this, Inside the source folder, I’ll create my component. And define our endpoint. And return it just like that. Of course, these items will be dynamic, so let’s take them as props and use them in our component. Now, instead of using the Next Image, let’s import our component. I’ll change my source, and as you can see, the image is here. You can also add the full image URL instead of just passing the path. Here, it says we can use ImageKitProvider to prevent writing urlEndpoint for each image, but I think it’s better to use it like this because since ImageKit uses context API, the component should be a client component, and we don’t want to change our server components. Okay, let’s look at the image manipulation. The only thing you should do is write here the transformation array and give your sizes.

### [10:00](https://www.youtube.com/watch?v=YP3BL4jIBHM&t=600s) Segment 3 (10:00 - 15:00)

You can also give the sizes like that, but we can add different options inside the transformation array. By the way, if you are re-sizing your images in this way, the parent should be relative. Just like that. We can also reduce the image quality. And we can give here any percentage. And now the image size is even smaller. Let’s see how to crop images. I’ll write cropMode: "extract" and I’ll add the positions that I want to start cropping. Let’s change the quality so we can see better. Actually, let me open the image in a new tab. As you can see, the x and the y positions are here. If I make it 50, it’ll start cropping after 2050 pixels. 60 and this is how it works Let’s rotate our image. 90 degrees. Just like that. By the way, you can give these options independently using different objects, in this case it’ll rotate first and after resize. Right now, I’ll try to add text to my image. To do that, I’m gonna be using a text layer. This type can be a text, image, or video. Let’s do the text. Here is gonna be the input. Let’s say LamaDev. I’ll add the font size, And finally, I’ll end my layer. I can also change the position. So I’ll say layer x 150 pixels and layer y 200 pixels. And make sure that you write them before the ending. You can also add an image. To do that, just change the layer type and the input, which is the image URL. What about the lazy loading? Let me add here some high quality images. And they are gonna be vertical so we can scroll down. If you don’t use lazy loading, all these images will be loaded together when you visit the page. But if you use it, images will be loaded only when you scroll down. And it increases our page speed. Let’s see. And this is what we want. We can also use blurred image placeholders. This is really important for the user experince. Let’s visit unsplash. com As you can see, it shows placeholders instead of showing a single color. And it’s really easy to do that with ImageKit. I’ll just say low quality image placeholder (lqip). Active will be true and the quality, let’s say 20 percent. And now, I’ll slow down my connection so we can see better. And perfect. We can also optimize the videos. Let’s create a Video component. We are gonna do exactlly the same thing, but this time we’ll be using the ImageKit Video Component. Let’s call our component on the homepage. I’ll add the source, sizes and the player controls. And the video is here and it’s size is much smaller right now. By the way they are not vertical, because here is should be display. Okay. Finally, let’s see how to upload images. It’s really easy; we’ll just use this upload component

### [15:00](https://www.youtube.com/watch?v=YP3BL4jIBHM&t=900s) Segment 4 (15:00 - 20:00)

it’s gonna render a file input, and we’ll be able to upload files. So let’s create our component. And use them inside. But to upload files to our media library, we need our private key. But since this component is a client component, we shouldn’t reveal the secret key. To prevent this, ImageKit requires a backend server. So we’ll send an authentication request, and we’ll get that request in the API, make the verification, and if everything is okay, it’s gonna send an access token. Using that token and this client component, we’ll upload our images. So, let’s create our API endpoint. Of course, you can change the name, let’s say upload-auth. Let’s add the GET request fuction. Now, we are ready to use the Upload component on the client side. Firstly we’ll need this public Id and the URL endpoint. Let’s define them here. As you can see, the file input is here. But we can’t upload any images because we are not authenticated. We have to send an authentication reques. To do that let’s create here a function called authenticator. I’ll say try catch And here, we are gonna make the api request. Remember the end point is api/upload-auth If the verification goes wrong, we’ll throw an error. If everything is okay, we’ll get the data. And remember it includes the signature, expire and the token, Let’s return them. And we can use this function here. You can give any file name but don’t have to because if you write useUniqueFileName, it’s gonna generate a different name for each file. If there is an error, we can handle it using this function. If it’s successful, we can see the final image using this function, We can also keep track of the progress using onUploadProgress. Let’s see. Okay, there is a typo here. And here is gonna be http The progress is here, and after the successful uploading process, we can see the image. So what you can do here? You can create a useState hook, that includes the error success and the progress states. You can show them somewhere here. You can also, get rid of this file input and show a custom element. So I’ll say display none. And create here a custom upload button. And when we click on this button, we’ll actually click on this upload component. To do that we can use the useRef hook, and call this here. And whenever we click on this button, we’ll call the ref and run a click event. Of course, the hook should be inside the component. Just like that. It’s that easy, guys! You can upload, optimize, and transform your images and videos with just one library. You don’t need anything else.

### [20:00](https://www.youtube.com/watch?v=YP3BL4jIBHM&t=1200s) Segment 5 (20:00 - 20:00)

As I said, ImageKit provides a free tier. You can upload thousands of images for free. You can find the link in the description. And I highly recommend you check the API documentation; you’ll find here tons of different features and their implementations. Again, the link will be in the description. And that’s all. I hope you liked it. If you learned something new today, please like the video. Don’t forget to follow Lama Dev’s social media accounts. I hope I’ll see you in the next tutorial. Goodbye.

---
*Источник: https://ekstraktznaniy.ru/video/37837*