teleren/devto huggingface dataset:
Using `createSelector` with Redux Toolkit
Tags: javascript, react, redux, performance
Published: 2023-09-08 16:13:39


### 1. **Introduction & Objective**:
`createSelector` is a powerful tool incorporated into Redux Toolkit, designed to create memoized selectors for Redux applications. Memoization ensures that derived data is recalculated only when its source data changes, optimizing performance and improving code maintainability. The primary objective of this pattern is to demonstrate the benefits of memoized selectors, especially in scenarios where repeated calculations can hinder application performance.

### 2. **Prerequisites**:
- Redux Toolkit installation.
- Basic understanding of Redux, its actions, reducers, and state management.

### 3. **Pattern Implementation**:

#### 3.1. **Problem Scenario**:
Imagine you're developing a task manager app using Redux. Users can add tasks, mark them as complete, and filter to view only completed or pending tasks. 

**State Structure**:
```javascript
const initialState = {
    tasks: [
        { id: 1, title: "Buy groceries", done: false },
        { id: 2, title: "Walk the dog", done: true },
        // ... more tasks
    ],
    filter: "ALL" // other values can be "DONE" or "PENDING"
};
```

The challenge is that each time the component renders, the list of tasks gets processed repeatedly based on the filter value. This redundant computation happens even if the tasks remain unchanged.

#### 3.2. **Solution Using `createSelector`**:
By employing `createSelector`, filtering only transpires when the tasks or filter value alters, eliminating redundant calculations.

```javascript
import { createSelector } from '@reduxjs/toolkit';

const getTasks = state => state.tasks;
const getFilter = state => state.filter;

const getVisibleTasks = createSelector(
    [getTasks, getFilter],
    (tasks, filter) => {
        if (filter === "DONE") {
            return tasks.filter(task => task.done);
        } else if (filter === "PENDING") {
            return tasks.filter(task => !task.done);
        } else {
            return tasks;
        }
    }
);
```
In your React component:
```javascript
const TaskList = () => {
    const visibleTasks = useSelector(getVisibleTasks);
    // render tasks
}
```

### 4. **Benefits**:
- **Performance**: By reducing unnecessary recalculations, application responsiveness is enhanced.
- **Reusability**: Selectors can be used across various components, promoting a DRY (Don't Repeat Yourself) codebase.

### 5. **Caveats & Considerations**:
- **Overhead**: Memoization's benefits should outweigh its costs. Use judiciously.
- **State Structure**: Modifying the Redux state's structure may necessitate selector updates.

### 6. **References**:
- [Redux Toolkit's createSelector documentation](https://redux-toolkit.js.org/api/createSelector)
- [React-Redux: Using Memoizing Selectors](https://react-redux.js.org/api/hooks#using-memoizing-selectors)
Install Docker and Docker Compose by single command and use it without sudo :)
Tags: docker, devops, ubuntu, linux
Published: 2023-09-08 16:09:05

I know it looks crazy but to be honest I am frustrated of searching "install docker ubuntu" and copy paste lots of commands every time. If it happens for you a lot, you can bookmark [this gist](https://gist.github.com/tuytoosh/b700f17f3ee3ad7f20d533e61de31c56) and just copy and paste it to install docker, compose and post installation commands. 
```
for pkg in docker.io docker-doc docker-compose podman-docker containerd runc; do sudo apt-get remove $pkg; done  &&
sudo apt-get update &&
sudo apt-get install ca-certificates curl gnupg &&
sudo install -m 0755 -d /etc/apt/keyrings &&
curl -fsSL https://download.docker.com/linux/debian/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg &&
sudo chmod a+r /etc/apt/keyrings/docker.gpg &&
echo \
  "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian \
  "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
sudo apt-get update &&
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin &&
sudo groupadd docker && 
sudo usermod -aG docker $USER && 
newgrp docker && 
sudo docker run hello-world
```
### A shorter way
If you don't want to copy such a long command you can easily run this one:
```
 /bin/bash -c "$(curl -s https://gist.githubusercontent.com/tuytoosh/b700f17f3ee3ad7f20d533e61de31c56/raw)"
```
It downloads the gist and runs the commands after getting root password.
I know there are some other standard ways to do this, like maybe using Ansible Playbooks or... but this is the easiest way!

Ciao e buon week-end :)
Satta Matka Dpboss Net Software Fix
Tags: webdev
Published: 2023-09-08 16:08:52

Hello Friends, I am posting this to learn about how to fix bug on my website of [Satta Matka](https://1sattamatka.in) Result Dpboss that provides people's fast Kalyan Matka, Madhur Matka Results for Free. Recently some tcp issue occurred in Satta Matka website Dpboss net. Can some help to fixmatka related. Call me on 9669138818.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1tlf4u3uz9l8orcnm94b.jpg)
Introduction
Published: 2023-09-08 16:04:35

Hey Everyone, My name is Rachit Chawla and Its my first blog on dev.to. I am currently a student of Computer Programming and Analysis at Seneca College. Also I'm currently on my co-op term working as an Automation Developer at Ontario Public Service. In this role, I am currently working with PowerShell scripting and Microsoft Azure for automating every manual tasks to reduce workload and increase efficiency. This blog is a part of OSD600 course at Seneca College. I am taking this course as I am big fan of open source and always wanted to contribute in open source projects but I am unaware of proper documentation and standards used for open source contributions. I am hoping to learn all the required stuff by the end of this course and I aim to be one of the 15k contributors to Linux's repo by Linus Torvald. Open Source interests me because it gives developers the power to customise the application they want to use, also a chance to help others and improve their skills. I found https://github.com/TheAlgorithms/Python interesting from the Monthly trending feed on Github as it has all the algorithms which help us improve time complexity and write better codes. I has about 1000 contributors which helped to code all the algorithms in Python which may help others for working or learning purposes. I myself was a student of Data Structures and Algorithms in Python Winter 2023 and hoping to even able to contribute to this repo itself, once I learn more about documentation & proper standards to be followed.
Simple Concurrent Tasks in Javascript
Published: 2023-09-08 15:56:33

Here is a very nice and tiny library from Samrith Shankar  [Concurent Tasks](https://github.com/samrith-s/concurrent-tasks)

And a demo : [DemoTasks](https://flems.io/#0=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAGhAGMB7NYmBvAHjmoCcIAHYgAjgdqAXgA6IEsW5xEAelnUAJmnwArOIphQIANw740MYrLTcsC+tQCuHDk2IBaYhjgBrOLKtZFFtNdv2Ti7u+FgQKurifMQAntwwYiCMAB7Gqhg6Lpw8xOIAfCyy7Fy8eaJo5SyEAIxlaHwsGHyEdmCJktJysgDmEMSEVgBG+HTmcNhc-Q4edH42dgxBbnD55Xzr6wDCljb2fAAqwSv1DbIYdYU1F1gY4XXrLINWxMT0fJba1K6JAs4cxAB9ZzLPgACgAlKsThsAMr7ACCACV9mtTk8XvR7g04DBqMQIG8IIpEnY4FYoMQViAsetUYUcXiCWgLrIbndKCAcbBGfQEIgQNVqohqgBmEAAXwo6GwuH5agQVFmjGY-LAVj8+LecFgMG4YKwcHBfGAqLsxBs9UMAHc+AAFDi0MI40Gg0kUPh2VRG4R5Y18VHrHHEfYQHC0Z4u72+k3Qjak0EGyGxyV8ROo8VJ8XlbN+Xn8YGuPjCMEQKN8FwxPxgxT0GBlv2omuGCEAbg28nLz0dGHx1AwUCgMXLik0ij4gyH-RgfG0gw4GA4MVRsH4HCL5att342pgutBAFke4R8PO0DWsBC+AAqPgAVgADPfwW2NhtTfByZT8OFDBwABL7PuAAyfAANTFqCAAGLCKLofDUFALhwIkBb5AWAAkwAQOKfBMKOfDhHwmEcDhBqFLBOh5JBz6vuUWYVGgaoaky8F2D2MCHCCoJoF4gwwGuxYikaMbrCu0RHOuyAALoBmAtBrqCYkQOu95tspLB8DxWB8RwamgaBwmvm+sbics+DcFYcCEKCBagqWfBGkZtLQvR6xmhapnuHR-r1OUsxwKu6q-uu1oHMEiJBfxl5rOUTE8vUAULoCBZwGCwnvmSFJwN+aC-gBwHruI4gtqakX6BgI77p+PCwKCnAwOxnHuBCNF0aiHJcrimpoHyIAAEwAOyICKABsEpSiAmA4HgIxwAqND0MqxB4IMtCKEOIl8HJixgNg0AxIg-ogDCMDdLQ04AKoAJLFaigwYF83QOuqiiHQAxNUfV9SKfUjSVJx0FA8mHYoC6uPJGBoN0MD-es22OHAEAAF4wId1T4CKdhYG2qJtQxNTGqiKSOP2EDdGgiDUPY-H-fR5RNJtgPA3woMcODp7Q7TOb4AWhMnNwFWwVDaNY7DPl02g6KvPUjO0EDHCIB9X0-X9d0Pa4T3hmeINgxDUMw3d8maAraC1mL8MOLtYSDod4gwgAogA4gA8vbfDXbdJwW4jKPChjouov4cDM9wtDhIwul4+UbIy0TMCpA4pPk5T1OR2g4odVoXVMr1g3CgAHBKUnikAA)

```js
function sleep (ms) {
  return new Promise((res, rej) => { 
    setTimeout(() => {
      res(ms)
    }, ms)
  })
}


const task = (i) => async (done) =>  { 
  done();   // automatically added by the library
  let r = await sleep(Math.random() * 500);       
  results.innerHTML += (`<div class="task">task${i} ended in ${r} ms</div>`);    
}

function createTasks (number = 3) {
  let tasks = []
   for (let i = 0; i < number; i++) {       
     tasks.push(task(i) )        
   }
  return tasks
} 
 
const runner = new TaskRunner() 
 
function start_tasks () {
  results.innerHTML = "";
  runner.addMultiple(createTasks()); 
}
```
How to Detect GPT Articles
Tags: gpt3, gpt4, ai, spam
Published: 2023-09-08 15:48:10

There is lots of GPT articles here that some of them feels like spam 🤣

Dont get me wrong I like GPT assisted codes and solutions. But not articles 😉

Lots of unintelligent "best bla bla bla tools" "best bla bla libraries"

Anyway here is 4 website and tools you can copy paste text to detect GPT / AI articles.

- https://www.zerogpt.com/

- https://gptzero.me/

- https://contentatscale.ai/ai-content-detector/

- https://x.writefull.com/gpt-detector

I recommend using more than one dont trust only one tool because sometimes they may give false possitives.
如何创建我们第一个Next项目
Published: 2023-09-08 15:40:38


# 项目实践前提需知道
本次的项目实践以`Next.js 13`版本为例子进行开发。在Next.js13版本中存在两套路由规制，分别为**App Router**和**Page Router**。本次我们将使用**App Router**进行项目实践,梦兽认为**App Router**更使用起来更顺手，更现代化。

# 安装并启动Next.js项目

在开始我们的Next.js项目之前，我们需要确保我们的系统满足以下要求：
- Node.js 16.8或更高版本
- 支持的操作系统包括macOS，Windows（包括WSL）和Linux

## 1. 自动安装
我们推荐使用create-next-app来创建一个新的Next.js应用，这个命令会为你自动设置好所有的东西。运行以下命令来创建一个项目：
```
npx create-next-app@latest
```
在安装过程中，你会看到以下提示：
```
What is your project named? my-app
Would you like to use TypeScript with this project? No / Yes
// 建议 Yest 
Would you like to use ESLint with this project? No / Yes 
// 建议 No
Would you like to use Tailwind CSS with this project? No / Yes
// 建议 Yes 
Would you like to use `src/` directory with this project? No / Yes
// 看你喜欢
Use App Router (recommended)? No / Yes
// 这里启动Yes
Would you like to customize the default import alias? No / Yes
// 建议Yes
```
在提示结束后，create-next-app会创建一个以你的项目名命名的文件夹，并安装所需的依赖。

## 2. 手动安装
如果你想手动创建一个新的Next.js应用，你需要安装必要的包：
```
npm install next@latest react@latest react-dom@latest
```
然后，打开package.json并添加以下scripts：
```
{
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  }
}
```
这些脚本对应于开发应用程序的不同阶段：
- dev: 运行next dev以在开发模式下启动Next.js。
- build: 运行next build以为生产使用构建应用程序。
- start: 运行next start以启动Next.js生产服务器。
- lint: 运行next lint以设置Next.js的内置ESLint配置。

接下来，创建一个app文件夹，并添加layout.tsx和page.tsx文件。当用户访问你的应用程序的根目录时，这些文件将被渲染。
在app/layout.tsx中创建一个包含必要的<html>和<body>标签的根布局：
``` ts
export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en">
      <body>{children}</body>
    </html>
  )
}
```
最后，创建一个带有一些初始内容的主页app/page.tsx：
``` ts
export default function Page() {
  return <h1>Hello, Next.js!</h1>
}
```
## 3. 包管理器推荐
在主流的包管理器`pnpm`,`yarn`,`npm`中梦兽编程推荐使用`pnpm`。因为`pnpm`很容易建立workspace应用。但如果是依赖关系比较中的项目建议使用lerna。lerna在workspace应用方面提供的服务与功能更加的全面。

## 4. 运行开发服务器
运行pnpm run dev来启动开发服务器，然后访问http://localhost:3000 来查看你的应用。你可以编辑app/layout.tsx或app/page.tsx并保存，然后在浏览器中看到更新的结果。

![screenshot-20230901-121815.png](https://x.imgs.ovh/x/2023/09/01/64f16686a6e9f.png)

以上就是关于如何安装并启动Next.js项目的教程。希望这对你有所帮助！

# 结语
这里是梦兽编程，本次的代码更新将会放在Github[本次项目的Github连接](https://github.com/rexleimo/rex-huaban)中。

[我的B站视频号](https://space.bilibili.com/106325238?spm_id_from=333.1007.0.0)更多视频动态。
为什么我们要学习Next.js
Tags: webdev, javascript, react
Published: 2023-09-08 15:38:58

本次的图册项目实践，主要面向两类人群。第一类是客户端浏览器想了解服务端开发的，第二类是正在学习Next.js，想获取的项目开发经验。
为什么我们需要学习Next.js
1. 技术分化导致“不健康”的知识体系

如今前后分离的社会现状，很多的正在做Web相关开发的技术人员都已经忘记了一个web的生态是如何进行的。

梦兽在一些群里面解答问题的时候，发现一个很有趣的现象。一个浏览器客户端的开发人员不会看HTTP协议。前端只知道调用后端的接口。后端做业务只考虑crud，其实是一件非常“不健康”的现象。
2. 客户端浏览器开发想了解服务端开发却不知道如何下手？

Next.js是一个基于React的JavaScript框架，它使开发者能够轻松地构建服务器渲染和静态生成的Web应用程序。Next.js提供了一种简单的方式来构建复杂的前端应用程序，同时还提供了许多优化性能的功能。

简单来讲就是如果你是一个React开发，那么你可以直接使用Next.js进行服务端的开发。你可以很容易的在React和Node.js中进行切换。而不像传统服务端渲染模板那种jsp,php,asp等模板引擎使用起来有割裂的感觉。

很多前端的开发小伙伴不知道如何进入服务端开发，我建议可以先从Next.js,Nuxt.js慢慢入手。等自己对服务端开发有了一定的了解后就可以去尝式学习Node.js中的生态Express。最后可以了解Nest.js中的微服务概念。如果这些都学好了，相信去用golang或者java都差不多的因为概念都是一样的。
3.全栈工程师的好处？

首先我要声明一下，所谓的全栈工程师不是市面那种半桶水就敢说自己是全栈工程。全栈工程师并不是所谓的前后端写代码就叫“全栈工程师”。如果你在这个过程中，无法锻炼出解决方案,快速定位问题,项目把控,需求分析。只是写写代码，如果在这个过程中，后端还是偏向后端，前端还是偏向前端的情况。那不是一个合格的全栈工程师，以为我个人的经验来看，全栈工程师应该在技术方面应该达到技术专家的75%的水平。剩下的25%就是技术专家应该做的事情极致的性能优化。

以个人7年的开发经验说说全栈工程师的好处：

    技能多样性：全栈工程师掌握了前端和后端的技能，他们可以处理从用户界面到服务器和数据库的所有事情。这种技能的多样性使他们能够在项目的各个阶段都发挥作用。如果你有想法就立即行动，而大部分（后端开发是有想法的但落实的时候发现找来模板后就不会改，或者使用Bootstrap这种模板）

    更好的项目管理：全栈工程师对整个技术栈有深入的理解，这使他们能够更好地管理项目，理解项目的各个部分如何协同工作，以及如何最有效地分配资源。

    更快的问题解决：全栈工程师可以快速定位和解决问题，因为他们理解前端和后端的工作原理。他们可以在问题出现时立即进行调试，而不需要等待其他团队成员。

    更好的职业发展：全栈工程师的技能使他们在职业发展上有更多的选择。他们可以选择专注于他们最喜欢的领域，或者继续作为全栈工程师工作。

从架构师的角度来讲可以分为三类解决方案架构师，技术专家,项目管理业务分析架构师。无疑全栈是以解决方案架构师和项目管理业务分析架构师这两个方向。如果你还是想往技术专家发展那可以背多点所谓的高级“面试题”。有些面试题还是有点技术含量的如果能把他们吃透的话。
4. 本次Next.js图册项目实践
1. 准备工作

    React开发经验
    HTTP协议基础

2. 这个系列得到了什么

    Next.js技术站开发
    Node.js操作 MongoDB
    Node.js操作Redis。利用内存数据库加快你的响应速度。
    SQL操作sqlite3
    类似花瓣发现的项目

结语

这里是梦兽编程，本次的代码更新将会放在Github本次项目的Github连接中。

我的B站视频号更多视频动态。
Display Current Year Short Code, WordPress
Tags: wordpress, php
Published: 2023-09-08 15:37:35

Add this to your functions.php


```
function display_current_year() {
    return date('Y');
}
add_shortcode('current_year', 'display_current_year');

```

This code will allow you to use [current_year] in your posts or pages, and it will output the current year.

Once the code is added to your theme or plugin, you can simply insert [current_year] anywhere in your posts, pages, or widgets to display the current year.





have fun with this little snippet :)

if you need more snippets like this have look at my tiny library [sinanisler.com](https://sinanisler.com/#codex)
Our Community Badges Page Just Got Better!
Tags: meta, community, badges, design
Published: 2023-09-08 15:35:49

Hey there, awesome DEV members! We have something special to share with you today. Drumroll, please... introducing our updated <a href="https://dev.to/community-badges" data-no-instant>Community Badges Page</a>!

We've been hard at work to enhance your experience and bring even more fun and motivation to your journey in our community. Let's take a quick tour of what's new:



### 🔍 Improved Sorting and Grouping:
We've given our badges a makeover! Now, you can easily see which badges are still up for grabs, the latest additions, and which ones are making waves. It's all about making your badge pursuit a breeze.

### 🏷️ Badge Categories:
Badges are now neatly grouped into three categories:

- **Community Badges:** Earn these by contributing to our community's wellness.
- **Coding Badges:** Showcase your skills and achievements with these badges.
- **Past Badges:** Explore badges from the archives and relive the good ol' times.

### 🧩 Handy Filters: 
We've added filters for your convenience. Want to see the most recent badges or arrange them alphabetically? You got it!


### 🎉 New Badges in Town: 
We’ve introduced some exciting badges recently, including the heartwarming <a href="https://dev.to/community-badges?badge=warm-welcome" data-no-instant>Warm Welcome</a>, the <a href="https://dev.to/community-badges?badge=icebreaker" data-no-instant>Icebreaker</a> badge, and the limited edition <a href="https://dev.to/community-badges?badge=thumbs-up-contest-winner" data-no-instant>Thumbs Up</a> badge for our fabulous mods.

### 🔄 Badge Revival: 
And we're not stopping there! In the coming weeks, we'll be bringing a few retired badges back to life and working our magic to freshen up some existing designs and give them a fresh vibe. Get ready for a badge makeover!

We hope you love the new Community Badges Page as much as we do! Thank you for being an incredible part of our community. Let's keep the positive vibes and knowledge sharing going strong!
Bun 1.0 is out the oven and support is here! 🥯
Tags: webdev, bunjs, news, javascript
Published: 2023-09-08 15:32:47

## [Bun 1.0](https://bun.sh/) is here! 

It's our absolute pleasure to share a small celebration and our first thoughts on this fully-baked runtime.

Let's dive in and take a look at Bun’s origins and what Bun 1.0 has to offer so without further ado, let’s get started and cheers to [Jarred-Sumner](https://github.com/Jarred-Sumner), Bun’s author and maintainer, may Bun live long and prosper!

**Let's go: [It's out of the Oven: Bun 1.0 support is here](https://platform.sh/blog/bun-support-is-here/?utm_source=devto&utm_medium=organic_social&utm_campaign=bun_blog&utm_id=platformsh_blog)!**
Set Up your GitHub Commit Signature
Tags: github, git, tutorial, codenewbie
Published: 2023-09-08 15:32:31


**Why and how you should set up your commit signature on GitHub**

## Introduction

Once you set up your commit signature, the commits are signed "Verified". Before then, they are signed "Unverified".

![Unverified and Verified Commits](https://pbs.twimg.com/media/F1viFOJWcAAj5lo?format=png&name=360x360)

## Why Should You Set Up Your Commit Signature?

1. **Data Integrity and Authenticity**: Commit signatures use cryptographic techniques to ensure the integrity and authenticity of your code changes. This means that others can be confident that the code attributed to you is legitimate and has not been altered by unauthorized parties.
    
2. **Build Trust and Reputation**: Commit signatures enhance your credibility as a developer, especially when contributing to open-source projects or collaborating with others. Trust is crucial in the software development community, and signed commits can help build a positive reputation.
    
3. **Secure Collaboration**: With signed commits, team members can easily verify the origin of changes, reducing the risk of accepting malicious or unauthorized code into the project. It fosters a more secure collaboration environment.
    
4. **Compliance and Legal Requirements**: In some projects and organizations, commit signatures may be mandatory to comply with legal or regulatory requirements, particularly for projects involving sensitive data or high-security applications.
    
5. **Code Review and Accountability**: Signed commits provide accountability during code reviews, ensuring that the author of each change can be easily identified. This encourages responsible development practices.
    

Although GitHub has provided straightforward guides and tools to set up your commit signature, I had difficulty setting up my commit signature because of the order in which the steps had been organized in the documentation.

I have listed the doc sources in the order I find clear and concise:

1. [Generate a GPG key](https://docs.github.com/en/authentication/managing-commit-signature-verification/generating-a-new-gpg-key)
    
2. [Add the GPG key to your GitHub account](https://docs.github.com/en/authentication/managing-commit-signature-verification/adding-a-gpg-key-to-your-github-account).
    
3. [Tell Git about your GPG key](https://docs.github.com/en/authentication/managing-commit-signature-verification/telling-git-about-your-signing-key).
    

Follow them in that order and you will not encounter any problems.

To sign your commits, you need to run the `git commit` command like this:

```bash
$ git commit -S -m "Commit Message"
```

However, to customize the command and make it easier to remember or quicker to type, learn how to create a permanent alias.
Security: How to Discover Hidden API's
Tags: security, tooling, infosec, api
Published: 2023-09-08 15:29:42

Unlock the secrets of API security! Don't miss our informative webinar hosted by[ True Positives, LLC](https://www.true-positives.com)in partnership with BLST Security. Go deep into the subject with industry experts like Dan Kuykendall, host of the [Dan On Dev](https://danondev.com/) Show. Register to attend: https://lnkd.in/gSVfTQJw.
Make your builds faster using Docker's RUN cache
Tags: java, docker, performance
Published: 2023-09-08 15:26:51

If you're like me and dislike taking coffee breaks while your entire .m2 directory rebuilds from scratch, or if you're frustrated at the thought of waiting again for the build to complete after making a tiny modification to your pom.xml, don't worry because Docker's [RUN cache](https://docs.docker.com/build/cache/#use-the-dedicated-run-cache) has got you covered.

In this post, I'll demonstrate how to create a Dockerfile that leverages the RUN cache to efficiently cache a container's .m2 directory. It's worth noting that I'm using a Spring Boot project as an example.

First, let's begin by using a JDK as the base image for 1st stage.

```
FROM eclipse-temurin:17-jdk-alpine AS build
```

Second, we mark a directory as our `WORKDIR`.
```
WORKDIR /workspace/app
```

Now, we copy few files necessary to generate our .m2 repository.
```
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
```

Next, this is where we use RUN cache.
```
RUN \
    --mount=type=cache,target=/root/.m2 \
    ./mvnw dependency:resolve-plugins dependency:resolve
```

Now, copy all the source files. We've waited until this point to ensure that the previous steps are cached by Docker and won't need to be executed every time there's a change in the project's code.

```
COPY src src
```

Again, We use the RUN cache to utilize the same local .m2 repository for the maven's `package` command.
```
RUN \
    --mount=type=cache,target=/root/.m2 \
    ./mvnw package
```

Now, we extract the jar so that the next stage can use the extracted files to run the application.
```
RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar)
```

Configure the 2nd stage of the docker build to run the application.
```
FROM eclipse-temurin:17-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=/workspace/app/target/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","com.example.SpringApplication"]
```

Voilà! Now you have an efficient Dockerfile that respects your valuable time.

Here's a complete version of the Dockerfile.
```
FROM eclipse-temurin:17-jdk-alpine AS build
WORKDIR /workspace/app
COPY mvnw .
COPY .mvn .mvn
COPY pom.xml .
RUN \
    --mount=type=cache,target=/root/.m2 \
    ./mvnw dependency:resolve-plugins dependency:resolve
COPY src src
RUN \
    --mount=type=cache,target=/root/.m2 \
    ./mvnw package
RUN mkdir -p target/dependency && (cd target/dependency; jar -xf ../*.jar)

FROM eclipse-temurin:17-jdk-alpine
VOLUME /tmp
ARG DEPENDENCY=/workspace/app/target/dependency
COPY --from=build ${DEPENDENCY}/BOOT-INF/lib /app/lib
COPY --from=build ${DEPENDENCY}/META-INF /app/META-INF
COPY --from=build ${DEPENDENCY}/BOOT-INF/classes /app
ENTRYPOINT ["java","-cp","app:app/lib/*","com.example.SpringApplication"]
```

_Signing off._