teleren/devto huggingface dataset:
리액트에서 props가 수정되면 컴포넌트가 리랜더링 될까? 과연?
Tags: react, rendering, javascript, programming
Published: 2024-01-14 05:39:16

예전에 문득 [React 공식 문서](https://react.dev/learn/render-and-commit#step-1-trigger-a-render)를 읽다가 흥미로운 내용을 발견했습니다.

> Step 1: Trigger a render 
> There are two reasons for a component to render:
> 1. It’s the component’s initial render.
> 2. The component’s (or one of its ancestors’) state has been updated.

자세히 읽어보니 랜더링 트리거 조건 중 "props가 변경된 경우"에 대한 언급이 없었습니다. 이전까지 "props가 변경되면 컴포넌트가 렌더링된다"라고 생각했었는데, 문서에는 그와 관련된 내용이 없어 궁금증이 생겼습니다. "실제로 prop가 수정되면 컴포넌트가 렌더링되는가?"에 대한 실험을 진행하기로 결정했습니다.

## 정의
먼저 "props가 변경되면 컴포넌트가 렌더링된다"라는 가정에서 시작하여, props가 변하는 것과 컴포넌트가 렌더링되는 것 두 가지를 분리하여 고려해봅시다.

## 컴포넌트 렌더링
React 공식 문서에 따르면 컴포넌트 렌더링은 해당 컴포넌트를 호출하는 것입니다. 아래의 예제를 살펴보겠습니다.

Counter 컴포넌트는 onClick과 count라는 두 개의 props를 가지고 있습니다.

```jsx
function Counter({
  onClick,
  count,
}) {
  return (
    <div>
      <button onClick={onClick}>카운트 올려!</button>
      <div>{`count : ${count}`}</div>
    </div>
  );
}
```

이 Counter 컴포넌트를 상태값인 count로 가지고 있는 StateCounter 컴포넌트를 살펴보겠습니다.

```jsx
let stateCounterRenderCount = 0;

function StateCounter() {
  stateCounterRenderCount += 1;

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

  const handleClick = () => {
    setCount((prev) => prev + 1);
  };

  return (
    <div>
      <Counter count={count} onClick={handleClick} />
      <div>{`StateCounter 컴포넌트 렌더링 횟수: ${stateCounterRenderCount}`}</div>
    </div>
  );
}
```

Counter 컴포넌트의 버튼을 클릭하면 count 상태가 증가하고, StateCounter 컴포넌트의 렌더링 횟수도 증가합니다. 
![run StateCounter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qyyi80vn063g2p3mnq06.gif)

이때 렌더링 횟수가 2번씩 증가하는 이유는 [React 공식 문서](https://react.dev/reference/react/StrictMode#fixing-bugs-found-by-double-rendering-in-development)에서 확인할 수 있습니다.

> Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) twice in development.

Strict Mode에서 순수 함수인지 디버깅하기 위해 의도적으로 함수를 두 번 호출합니다. 따라서 state를 수정할 때마다 stateCounterRenderCount가 2씩 증가합니다.

## Props 수정
이제 렌더링에 영향을 미치는 다른 요소들은 배제하고, Counter 컴포넌트를 가지고 있는 PropsCounter 컴포넌트를 살펴보겠습니다.

```jsx
let propsCounterRenderCount = 0;
let count = 0;

function PropsCounter() {
  propsCounterRenderCount += 1;

  const handleClick = () => {
    count += 1;
    console.log({ count }); // count가 실제로 증가하는지 확인하기 위한 콘솔 로그
  };

  return (
    <div>
      <Counter count={count} onClick={handleClick} />
      <div>{`PropsCounter 컴포넌트 렌더링 횟수: ${propsCounterRenderCount}`}</div>
    </div>
  );
}
```

Counter 컴포넌트의 버튼을 클릭하여 count를 증가시켜도 콘솔에는 count가 증가하지만 PropsCounter 컴포넌트의 렌더링 횟수는 증가하지 않습니다.
![run PropsCounter](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vg825rdqeakbec7dvfc9.gif)

## 결론
props가 수정되어도 렌더링이 자동으로 발생하지 않습니다. 렌더링이 트리거되는 순간은 리액트 공식 문서에서 설명한 대로 다음과 같습니다:

1. 컴포넌트의 초기 렌더링
2. 컴포넌트(또는 상위 컴포넌트 중 하나)의 상태가 변경되었을 때

즉, props가 변경되더라도 렌더링은 상태의 변화에 의해 주로 발생하며, props의 변경으로 인한 렌더링은 해당 props가 컴포넌트 내부에서 상태로 사용되고 상태가 변경될 때 발생합니다.
Open-Source Trending GitHub Repositories
Tags: beginners, frontend, opensource, webdev
Published: 2024-01-14 05:22:09

**## 01. Screenshot To Code**
This simple app converts a screenshot to code(HTML/Tailwind CSS, React Vue, or Bootstrap). You can now also enter a URL to clone a live website!
[screenshottcode.com](screenshottcode.com)

**## 02. Plane**
Open-source alternative for project management tools such as Jira or Linear. Helps you track your issues, epics, and product roadmaps in the simplest way possible.
[plane.so](plane.so)

## 03.PocketBase
PocketBase is an open-source Go backend, consisting of an embedded database, built-in files & user management, a convenient Admin dashboard, and the simplest Rest-ish API.
[pocketbase.io](pocketbase.io)

## 04. daisyUI
The most popular, free, and open-source component library for Tailwind CSS. They have 55+ components built-in to use.
[](daisyui.com)

## 05. SuperDuperDB
Bring AI to your database, integrate, train, and manage AI models and APIs directly with your database and your data.
[superduperdb.com](superduperdb.com)
Destiny: A Tool to Manage Cluttered Folders
Tags: go, cli, tooling
Published: 2024-01-14 05:21:23

## Table of Contents

  - [Description](#description)
  - [How to Use](#how-to-use)
    - [Installation](#installation)
    - [Organizing Files](#organizing-files)
  - [How it Works](#how-it-works)
  - [Conclusion](#conclusion)

## Description

Destiny is a command line tool written in `go` that simplifies the organization of cluttered folders. If you've ever struggled with maintaining a tidy file system, Destiny is here to make your life easier. Unlike a traditional shell script, Destiny includes checks for excluded files and provides a more manageable and user-friendly experience.

## How to Use

### Installation

If you are on macOS or Linux, use the following command to install Destiny:

```bash
curl https://raw.githubusercontent.com/bhumit070/destiny/main/install.sh | bash
```

### Organizing Files

- To organize files in the current folder, run:

```bash
destiny
```

- To organize files in a specific folder, provide the folder path as an argument:

```bash
destiny /path/to/folder
```

## How it Works

Destiny employs a simple yet effective approach to file organization:

1. File Scan:

- Destiny scans all files in the target folder.

2. Folder Creation:

- For each unique file extension, Destiny checks if a corresponding folder exists.
    If the folder does not exist, Destiny creates a folder with the same name as the file extension.
    File Movement:
    Destiny moves each file to the folder associated with its file extension.

3. Example: If you have a file named hello.txt, Destiny creates a folder named txt (if not exists) and moves the file into it.

## Conclusion

Destiny is a user-friendly tool that significantly improves the organization of your files. Whether you're dealing with a cluttered workspace or aiming for a more systematic approach, Destiny has got you covered. For suggestions or feedback, please create an issue on the [GitHub repo](https://github.com/bhumit070/destiny).

Also if you like Destiny, please star the repo.
Keep Knowledge in Plain Text
Tags: codenewbie, softwaredevelopment
Published: 2024-01-14 05:06:34

| 🔴 **Disclaimer**: This post is enhanced with AI assistance.|
|--------------|

> Plain text won’t become obsolete. It helps leverage your work and simplifies debugging and testing.
>   ~ Tip #25 from the book "The Pragmatic Programmer"

---


In realms of code, where circuits hum and sing,
Beware the siren of the encrypted spring.
No fancy formats, cloaked in cryptic veils,
For plain text whispers, where true knowledge trails.

Forget the PDFs, the docs in gilded frames,
Plain text's the hero, unburdened by their games.
No hidden macros, no parsing's endless maze,
Just bytes and lines, a symphony of days.

Like trusty parchment, weathering every storm,
Plain text endures, a code-forged, timeless form.
No software sunset, no upgrade's cruel decree,
It laughs at versions, eternally free.

Debugging's torch, it cuts through tangled lies,
No cryptic symbols, where confusion multiplies.
With open eyes, you see the logic's dance,
Each line a mirror, reflecting truth's expanse.

Testing's armor, forged in plain text's might,
Mocks fancy wrappers, veiled in digital night.
With scripts and tools, you probe the code's embrace,
No hidden corners, escaping logic's chase.

So raise your keyboard, a banner held on high,
Let plain text's wisdom guide you as you code and fly.
For in the realms of bytes and screens, where logic takes its stand,
Plain text's the hero, making software grand.

So code with clarity, let every line unfold,
A testament to truth, in characters of old.
And leave in your wake, a legacy so bright,
Where plain text whispers, "Knowledge takes its flight."

---

|✍ **Powered by**: *Google Bard*|
|--------------|
Text Utils
Published: 2024-01-14 04:37:36

Hi Devs, I recently made a Text Util app while learning React. I will working on it and will be upgrading it over time.

[Text Utils App](https://text-utils-snowy-one.vercel.app/)


![Preview](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/injf4yeiklvrjvkccemc.png)
POS-Tagger in Rust
Tags: rust, machinelearning, java, opensource
Published: 2024-01-14 03:35:46

Hello developers! 
I've build a `nltk`-inspired parts-of-speech tagger in Rust - [postagger.rs](https://github.com/shubham0204/postagger.rs)

It is a re-write of the `AveragePerceptronTagger`, authored by Matthew Honnibal for `nltk` in Python. It uses the weights, classes and POS tags but performs the inference in Rust, with wrappers written in C and Java.

Here's the Rust API,

```rust
pub mod perceptron_tagger;
use self::perceptron_tagger::PerceptronTagger;
use serde_json ;

fn main() {
    let tagger = PerceptronTagger::new( "tagger/weights.json" , "tagger/classes.txt" , "tagger/tags.json" )  ; 
    let tags = tagger.tag( "shubham was good" ) ;
    for tag in &tags {
        println!( "{} {} {}" , tag.word , tag.tag , tag.conf ) ; 
    }
}
```

the C API,

```c
#include "postagger.h"
#include <stdio.h>
#include <stdlib.h>

int main( int argc , char** argv ) {
    PerceptronTagger* tagger = tagger_create( "tagger/weights.json" , "tagger/classes.txt" , "tagger/tags.json"  )  ;
    const TagResults* results = tagger_annotate( tagger , "the quick brown fox jumps over the lazy dog" ) ; 
    for( int i = 0 ; i < results -> num_tags ; i++ ) {
        printf( "word=%s , tag=%s , conf=%f \n" , results -> tags[i].word , results -> tags[i].tag , results -> tags[i].conf ) ; 
    }
    tagger_release( tagger ) ;
}
```

and the Java API,

```java
import java.util.List;
import pos.tagger.POSTagger.POSTag;

public class Main {

    public static void main( String[] args ) {
        POSTagger tagger = new POSTagger(
            "weights.json", 
            "tags.json", 
            "classes.txt"
        ) ; 
        List<POSTag> tags = tagger.tag( "the quick brown fox jumps over the lazy dog" ) ;
        for( POSTag tag : tags ) {
            System.out.println( tag.getWord() + " " + tag.getTag() ) ;
        }
    }

}
```

If you find the project interesting, do ⭐ star the project and consider contributing your thoughts and suggestions!
Help me add more features / resolve issues in react-formvik
Tags: webdev, programming, tutorial, react
Published: 2024-01-14 03:18:50

Sometime back I created this React library for forms, which helps user to create dynamic forms easily.

I am continuously working on it.
Though, I also need people to support me on this by using it and report some issues and awesome features.

This will give me enough motivation to work on it and continue building awesome libraries.

Please try it out once at-least!
If you don't have that much time, go through the docs and live examples and share your thoughts on Github issues or here.
Feel free to put negative feedbacks, I learn from it.
https://www.npmjs.com/package/react-formvik

Thanks in Advance!
My first game!
Tags: webdev, battleshipsgame, firstgame, beginners
Published: 2024-01-14 02:40:43


Battleships Ahoy!

Delighted to share my first self-made game crafted with Python and utilizing Git/GitHub. While it's currently straightforward, there's room for complexity.

This milestone marks progress since commencing my coding journey in late 2023, proving to myself that I can learn anything if I stick to it.

Anticipating future enhancements, I'm thrilled to witness the growth ahead. 

Enjoy the voyage! ⚓🚀
(https://github.com/Kkeats9898/Battle-ships-game-.py)
How do we measure productivity?
Tags: productivity, watercooler
Published: 2024-01-14 02:25:44

Is it the number of items that we cross off our to do list? The number of emails we send each day? Or the number of lines of code we write?

&nbsp;

The answer is **it depends.**

&nbsp;

The real measurement is **how much closer did we get to the goal?**

&nbsp;

> *Every action that brings a company closer to its goal is productive. Every action that does not bring a company closer to its goal is not productive.*
>
> Eliyahu M. Goldratt, The Goal


&nbsp;

When people talk about their “productive” day, they will mention actions like answering x number of emails, attending x number of meetings, writing x number of pages, or pushing out x numbers of lines of code. 

&nbsp;

The real problem is NOT that they completed those tasks, but rather they did not take a step back and think of what the actions were supposed to lead to.

&nbsp;

There is a famous quote by Lewis Carroll in *Alice in Wonderland*, and I think it’s something important to remember in terms of the importance of knowing where you’re going:

&nbsp;

> *“One day Alice came to a fork in the road and saw a Cheshire cat in a tree. ‘Which road do I take?’ she asked. ‘Where do you want to go?’ was his response. ‘I don’t know,’ Alice answered. ‘Then,’ said the cat, ‘it doesn’t matter.”*
>
> Lewis Carroll, Alice in Wonderland


&nbsp;

When there is no goal or destination, then it doesn’t matter how hard you work, how much time you spend, if you are using the perfect productive app, or x amount of items you crossed off of your to do list.

&nbsp;

If you are trying to get from Washington to New York, it’s not worth measuring the steps taken, the time spent on the freeway, or even the speed you are going. **The importance is knowing that you’re heading in the right direction.**

&nbsp;

Therefore, if we are trying to be productive, we then there are two steps we need to take:

1. **Have a goal**
2. **Do actions that will bring you closer to that goal**

&nbsp;

So how do we become really productive?

&nbsp;

It may seem like all actions are created equal, but some actions will have greater effects than others. 

&nbsp;

It’s important to remember the Pareto Principle: **that 80% of the outcomes come from 20% of the causes.**

&nbsp;

Therefore, try to focus on the 20%, or the actions that will get you closer to your goal than ever before. Then, you will truly be productive.

&nbsp;

Hopefully this article gets you to be more productive! Get out there and start doing your [best work today!](https://flowmodoro.com)
VAR ... the Almighty Yet Obsolete
Tags: javascript, webdev, learning, architecture
Published: 2024-01-14 01:46:45

A few days ago I read an article that caught my attention, it talked about var. I’ll briefly explain about it.

Currently to declare a variable in JS we use let, const and to a lesser extent var. But var existed before let and const, in fact ‘var’ was the only type of variables within JS.

So why don't we currently use var?

While var has been around since the beginning of JS, it hasn't changed much since then, however JS has. In fact it has changed so much that now var could cause us problems.

The reason?

Var ignores code blocks and this is because a long time ago Javascript did not have lexical environments, it can be declared again and in the same way var is always processed at the beginning of a function.

Let's first review the first case. When we use var inside an 'if statement' or inside a 'loop', we can access var outside the block (which does not happen with let or const).

```
if (true) {
     var testVar = true;
     let testLet = false;
}

console.log(testVar); // true
console.log(testLet); // Reference error testLet not defined
```

The second case is very simple, var can be declared over and over again, unlike let or const, which would give us an error mentioning that the variable has already been declared.

```
var testVar = 0;
var testVar = 'new value';
console.log(testVar); // new value

let testLet = 'value';
let testLet = 'no new value'; // SyntaxError 'testLet' has already been declared;

```

The third case, in functions, is my favorite. Var can be declared below where they are used. 

```
function test() {
    testVar = 'some value';
    console.log(testVar); // some value
    var testVar;
}

console.log(testVar);  // undefined
```

To avoid this strange behavior, programmers invented IIFE (immediately invoked function expressions). 

```
(function() {
  // some code
})();

(function() {
  // some code
}());

!function() {
  // some code
}();

+function() {
  // some code
}();
```

They are NOT currently used, DO NOT CODE IT but it is very nice to know a little history about something you are passionate about. By the way, you can see the article about var and all JS stuff [here](https://javascript.info/).
Copilot or Wakatime VSCode extensions not working on WSL: Solution
Tags: vscode, wakatime, githubcopilot, wsl
Published: 2024-01-14 01:20:19

**TLDR:** add 
```json
"remote.extensionKind": {
        "WakaTime.vscode-wakatime": [ "ui" ],
        "GitHub.copilot": [ "ui" ],
        "GitHub.copilot-chat": ["ui"]
}
```
to your vscode `settings.json`

I recently encountered a problem with Windows' WSL. When opening a project from the WSL in Visual Studio Code, two of my extensions stopped working. Wakatime and Github Copilot. After a lot of debugging, it seems to be a web request certificate error that WSL makes. To fix this, simply run the extensions locally on Windows instead of on WSL by editing your VSCode `settings.json` (see TLDR).

`ui` stands for running the extension locally on Windows and `workspace` would mean running it on WSL.

There are also other solutions, such as [ignoring the unauthorised requests](https://dev.to/cubbk/make-github-copilot-work-in-wsl-with-zscaler-3b5n) or using a VPN or a proxy. But I think this is the easiest one.
SupabaseJS and select join with count
Tags: supabase, javascript, react, supabasejs
Published: 2024-01-14 01:01:16

Hi, if you are looking for how to get count of the second select in supabase this is your post :)

```
return supabase
  .from('game')
  .select(`
    id,
    name,
    users(count)
  `)
  .eq('id', id)
  .then(({data, error}) => {
    if (error) {
      return Promise.reject(error.message);
    }

    return Promise.resolve({
      id: data[0].id,
      name: data[0].name,
      usersCount: data[0].users[0].count
    });
  });
```

Have fun!
Understanding C# Delegates and Events
Tags: csharp, beginners, programming, tutorial
Published: 2024-01-14 00:34:21

## Introduction

C# is a powerful and versatile programming language that has gained popularity in recent years due to its efficient and user-friendly nature. One of the key features that make C# stand out is the concept of delegates and events. Delegates and events play a crucial role in enabling communication between different objects, making it easier to develop complex applications. In this article, we will dive into the world of C# delegates and events and understand how they work and their advantages and disadvantages.

## Advantages

- **Flexibility with Callback Functions**: Delegates in C# allow developers to create callback functions, allowing for a more flexible and dynamic approach to programming. This means that instead of explicitly specifying the method to be called, the delegate can be passed as a parameter, making the code more efficient and concise.
- **Enhanced User Interaction through Events**: Events, enabled by delegates, are an essential tool for developing applications with user interaction. They allow objects to notify other objects when a specific action occurs, making it easier to handle user inputs and respond accordingly.

## Disadvantages

- **Complexity for Beginners**: One of the major drawbacks of delegates and events is that they can be difficult to understand for beginners. The syntax and concepts may seem confusing, leading to potential errors and bugs in the code.
- **Potential Performance Issues**: Managing multiple events and delegates can be cumbersome and can potentially slow down the application's performance.

## Features

- **Multicast Delegates**: Enable multiple methods to be subscribed to a single event, improving the responsiveness of the application.
- **Anonymous Methods and Lambda Expressions**: Make the code more concise and readable, improving its overall efficiency. These features allow for more flexibility and functionality in the code.

### Example: Using Delegates and Events

```csharp
public delegate void Notify();  // Delegate declaration

public class ProcessBusinessLogic
{
    public event Notify ProcessCompleted; // Event declaration

    public void StartProcess()
    {
        Console.WriteLine("Process Started!");
        // Some process logic here...
        OnProcessCompleted();
    }

    protected virtual void OnProcessCompleted()
    {
        ProcessCompleted?.Invoke();
    }
}
```

This example demonstrates how to declare and use a delegate and an event to notify other parts of an application when a process is completed.

## Conclusion

In conclusion, delegates and events are essential components of C#, enabling communication and interaction between objects in a flexible and efficient way. While they may come with some disadvantages, the advantages and features provided make it a valuable tool for developers, especially in developing complex applications. Understanding delegates and events will not only enhance your programming skills, but it will also open up a world of possibilities for creating innovative and dynamic applications.
How Does Bravery Affect Software Success?
Tags: discuss
Published: 2024-01-14 00:00:00

---
published_at : 2024-01-14 00:00 +0000
---
Bravery in software success — share your triumphant moments! How has courage paid off for you?
<br>
Connect with DEVteam for more discussions and camaraderie! 🌐 {% embed https://dev.to/devteam %}
Caption This! 🤔💭
Tags: watercooler, discuss
Published: 2024-01-14 00:00:00

---
published_at : 2024-01-14 00:00 +0000
---
Time to show off your captioning chops! We need your genius to bring this captivating moment to life!

![A seal looking silly](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zv2495n9ced830lsr3l3.jpg)

---

Follow the DEVteam for more online camaraderie!
{% embed [https://dev.to/devteam](https://dev.to/devteam) %}
Code is a liability, not an asset
Published: 2024-01-15 11:33:08

---
title: Code is a liability, not an asset
published: true
date: 2024-01-14 00:00:00 UTC
tags: 
canonical_url: https://www.oliverdavies.uk/archive/2024/01/14/code-is-a-liability-not-an-asset
---

Something I mentioned during my [podcast episode with Mike Karthauser](https://www.oliverdavies.uk/podcast/7-mike-karthauser-testing-legacy) is a quote I saw recently:

> Code is a liability, not an asset.

The more code you write, the more you have to maintain.

The more complex the code is, the harder it is to maintain.

For example, when adding a new page to a Drupal application, should you write a custom route, a Controller, and a Repository and write accompanying tests, or should you use the Views module?

Both can give the same result.

One involves writing and maintaining custom code; the other uses a no-code approach available in Drupal, which creates the page and output based on your selections.

There isn't a correct answer.

The option you choose will depend on what problem you're solving, what deadlines you're working to, and any precedents set within the project.

It also depends on whether you want to maintain the code you write over time, fix any bugs, refactor it, and upgrade it as part of major Drupal version upgrades.

Like a house, car or pet, any code you write will need ongoing care and maintenance in the future - not just now.

 P.S. If you're creating a new Drupal module, try my [free Drupal module template](https://github.com/opdavies/drupal-module-template).