teleren/devto huggingface dataset:
Double Trouble: Why Your React Component Loads Twice with useMemo
Tags: react, webdev, usememo, javascript
Published: 2024-02-22 01:03:42

## Introduction

You're diligently crafting your React app, leveraging the power of the `useMemo` hook to optimize performance. But wait, why is your component rendering twice during local development, despite your best efforts? Fear not, fellow developer, this phenomenon has a rational explanation and solutions!

### The Culprit: React's Strict Mode

The reason behind the double rendering lies in React's **Strict Mode**, a development-only feature designed to catch potential issues. It achieves this by intentionally rendering components twice, allowing for more thorough testing and identification of side effects. This can be helpful in preventing bugs, but it can also lead to confusion when trying to understand rendering behavior.

### How `useMemo` Gets Caught in the Crossfire

While `useMemo` memorizes expensive calculations, it doesn't prevent double rendering triggered by Strict Mode. This is because the hook only caches the result based on its dependencies, not the rendering context. So, during the second render, even with the same dependencies, the calculation runs again due to the separate rendering pass.

### Strategies to Tame the Double Render

Here are some options to address the double rendering:

1. **Disable Strict Mode:** If you're confident your component is functioning correctly, you can temporarily remove `React.StrictMode` from your `index.js` file. This will stop the double rendering but remember to re-enable it before production to maintain strict testing.
2. **Refactor with `useCallback`:** If your component relies heavily on `useMemo`, consider using `useCallback` instead for functions passed as props. `useCallback` memoizes the function itself, preventing unnecessary re-creation during the second render.
3. **Embrace the Double Render:** If the double rendering doesn't cause performance issues and you're comfortable with it, simply acknowledge it as a side effect of Strict Mode and move on.

### Beyond the Basics

Remember, these are just starting points. For a deeper understanding, explore these resources:

* **React Strict Mode Documentation:** [https://legacy.reactjs.org/docs/strict-mode.html](https://legacy.reactjs.org/docs/strict-mode.html)
* **useMemo Hook Documentation:** [https://react.dev/reference/react/useMemo](https://react.dev/reference/react/useMemo)
* **useCallback Hook Documentation:** [https://react.dev/reference/react/useCallback](https://react.dev/reference/react/useCallback)

By understanding the reasons behind the double rendering and employing the appropriate solutions, you can confidently navigate the nuances of React development and optimize your components for performance. Happy coding!
Ruby Array Methods
Tags: beginners, programming, ruby
Published: 2024-02-22 00:40:05

Let's talk about Ruby's array methods... but first, what is an array?

Arrays are dynamic collections of elements, capable of storing any data type and adjusting in size as needed. With built-in methods for sorting, iteration, and transformation, arrays in Ruby offer flexibility and efficiency for managing collections of data.

Here are some methods demonstrating some of Ruby array's versatility:

**.sample**
This method returns a random element (or elements) from the array. Here are some examples: 

![.sample code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/de98qh2p1lazb1rgpd9b.png)

If we want multiple elements:

![.sample code sample with multiple elements](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bayiu2vdy5x3cf74iesv.png)

**.sort**
This method returns a new array with the elements of the original array but it sorts the elements of the array in ascending order. Let's see this method in action:

![.sort code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v5jdzweo3xvet3qusft9.png)

**.count**
Ruby's .count returns the number of elements in the array that meet certain conditions. It also returns the number of elements in a list, when given no arguments. If given an argument, returns the number of times that argument occurs in the array. In these instances, this method returns an **Integer**

![simple .count code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kpuyo8e0nndi552tgd5s.png)


![complex .count code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ng2rnqsg0yvsdnm899q1.png)

**.push**
This method adds one or more elements to the end of any Array and returns a modified array. For example:

![.push code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ejooyj72c5xu17otzl06.png)

**.at**
This method takes in an Integer argument and returns the element in the specified index of an Array. 

![.at code sample](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kjostkx0j10zj90wdane.png)

**.join**
You can think of this method as the inverse of String's .split method. It combines the elements of the array into a single string, separated by a specified delimiter. Here are some examples of using these different delimiters:

![.join code samples](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/b3mgh5yxct5brf3oqvzx.png)


Of course, there are other array methods such as .sum, .min & .max, and .include. I hope these have been helpful for your Ruby learning journey.

Until next time, Happy Coding!
How to use zlib (a C library) from Perl with SPVM
Tags: spvm, perl, zlib, c
Published: 2024-02-22 00:03:59

How to use zlib (a C library) from Perl with <a href="https://metacpan.org/pod/SPVM">SPVM</a>.

See <a href="https://github.com/yuki-kimoto/SPVM/tree/master/examples/native/zlib">an example to bind zlib to SPVM</a>

SPVM provides a way to bind C language libraries and call them from Perl.

When binding C libraries to Perl, you typically write XS, but SPVM offers an alternative approach.

MyZlib.spvm

```
class MyZlib {
  native static method test : void ($ouf_file : string);
}
```

MyZlib.c

``` C
#include "spvm_native.h"
#include<stdio.h>

#include "zlib.h"

static const char* FILE_NAME = "MyZlib.c";

int32_t SPVM__MyZlib__test(SPVM_ENV* env, SPVM_VALUE* stack) {
  
  void* obj_out_file = stack[0].oval;
  
  if (!obj_out_file){
    return env->die(env, stack, "$ouf_file must be defined.", __func__, FILE_NAME, __LINE__);
  }
  
  const char* out_file = env->get_chars(env, stack, obj_out_file);
  
  char buf[]="0123456789abcdefghijklmnopqrstuvwxyz\n";
  int cnt = 0;
  gzFile zp;
  
  zp = gzopen(out_file, "w9");
  if(zp == NULL){
    return env->die(env, stack, "gzopen failed.", "MyZlib.c", __func__, FILE_NAME, __LINE__);
  }
  
  for(cnt = 0; cnt < 100; cnt++){
    gzputs(zp, buf);
  }
  
  gzclose(zp);
  
  return 0;
}

```

MyZlib.config

```
use strict;
use warnings;

use SPVM::Builder::Config;

my $config = SPVM::Builder::Config->new_gnu99(file => __FILE__);

$config->add_lib('z');

$config;
```

zlib.pl

```
use strict;
use warnings;

use FindBin;
use lib "$FindBin::Bin/lib";

use SPVM 'MyZlib';

my $out_file = "$ENV{HOME}/tmp/output.gz";

SPVM::MyZlib->test($out_file);
```

A compressed file "output.gz" will be output.
My Content Creation In Its Infancy
Tags: blogging, contentcreation
Published: 2024-05-04 09:07:49

---
title: My Content Creation In Its Infancy
published: true
date: 2024-02-22 00:00:00 UTC
tags: blogging,contentcreation
canonical_url: https://billyle.dev/posts/my-content-creation-in-its-infancy
---

After years of procrastination and hesitation, my blog is _finally_ online. It's been a long time coming ever since I began to learn how to code in 2015.

In that timeframe, I have used several blogging tools, ranging from easy to difficult - WordPress, GatsbyJS, and, daringly, Hugo (I had no Golang experience at the time). I hadn't committed to any because I was still exploring programming in general.

When Astro landed on my radar, I chose it for many reasons. One of the most convincing was that it is a static site generator with the promise of shipping minimal JavaScript.

Its simplicity and versatility are by far the most advanced I've seen in a static site generator. I'm very glad that I can blog with such an amazing tool. Thank you, Astro team, for delivering a pleasant experience.

## So why blog now?

It's 2024, and artificial intelligence is running rampant. People's attention spans are getting shorter due to information overload, and almost every market is saturated with regurgitated content.

Who dares to start a blog in this day and age?

As someone who fancies an easygoing lifestyle, I couldn't care less about this environment. The joy and calmness that result from writing are therapeutic.

I'm mostly alone with my thoughts and equipped with a blinking cursor for the majority of my day. What better way could I lay out these unspoken feelings and thoughts into a post other than coding?

## Uncharted territory

I'm discovering what it is to become a creator and how difficult navigating the path is, even when there are plenty of guides on it. That's why blogging, I think, is the easiest entry of them all.

Re-engagement can be low, and there is no significant time-sink into editing. The hard part is coming up with ideas and putting in the time to do the work.

Slowly, but surely, I'll refine my process as I author dozens more posts like this one while also building new features to supplement your reading.

## What's current with me

I'm currently involved in building a startup as a solo founder in hopes of generating income. The world of startups is alien to me, and that is why I'm starting to blog. I want to document my journey in a safe environment.

I don't know startup lingo. Furthermore, I don't have a social network. And I surely don't know how to launch a product. To sum it all up, I don't know what I'm doing and am just trying things out until something sticks.

So hopefully, I'll be able to reveal to you cool articles, techniques, products, and more that I think you might be interested in along the way.

If you made it this far, thank you for taking the time to read this. And if you happen to enjoy this or encourage me to go on, please reach out. I would love to hear any feedback or advice you have to offer.

With that, I bid you farewell until next time.
Diffy and visual regression testing
Published: 2024-03-01 23:29:14

---
title: Diffy and visual regression testing
published: true
date: 2024-02-22 00:00:00 UTC
tags: 
canonical_url: https://www.oliverdavies.uk/archive/2024/02/22/diffy-and-visual-regression-testing
---

I recently recorded an episode of [Beyond Blocks](https://www.oliverdavies.uk/podcast) with Yuri Gerasymov, who runs Diffy.

He and I discussed visual regression testing, why you'd use it, and some features Diffy offers.

I usually write a combination of browser, kernel and unit tests within an application framework like Drupal and Symfony or behavioural tests with Behat.

These validate that my logic works as expected and that functions return the correct results or pages return the correct response codes and content.

There are types of issues, though, such as breakages within the page layout or structure, which these tests won't discover but can be identified by visual regression tests that compare before and after screenshots.

I added to my website during the recording and can see what value it offers as an additional layer of testing on top of the tests I already write.

P.S. Do you need immediate access to an expert Drupal Developer? With my [Drupal development subscription](https://www.oliverdavies.uk/subscription), make unlimited requests for a fixed monthly price in less time than posting to a job board!
Review: Learn Concurrent Programming with Go
Tags: books, go
Published: 2024-02-27 13:47:42

---
title: Review: Learn Concurrent Programming with Go
published: true
date: 2024-02-22 00:00:00 UTC
tags: Books,Go
canonical_url: https://jonfriesen.ca/articles/concurrent-programming-with-go
---

Go has been my primarily language for the last ~6 years, however, until now I’ve primarily been a consumer of libraries that employ high levels of concurrent programming and had minimal experience implementing these patterns on my own let alone in a production setting.

I stumbled upon [Learn Concurrent Programming with Go](https://www.manning.com/books/learn-concurrent-programming-with-go) in a [Reddit post](https://www.reddit.com/r/golang/comments/18b86aa/my_concurrent_programming_book_is_finally/) by the author, [James Cutajar](https://www.cutajarjames.com/) announcing it’s release.. My first impression was “that’s neat” and moved along with my daily reddit based procrastination routine before quickly scrolling back searching in earnest for as this is a skill I wanted to get better at.

 ![book cover photo](https://jonfriesen.ca/_next/static/media/learn-concurrent-programming-with-go.77e18134.jpg)

James does a fantastic job of reviewing the foundational requirements for a developer, touching on concurrency topics like processes vs threads, and then dives into patterns using the Go standard library tooling to demonstrate these. Taking time to explain topics like communicating sequential processes (CSP) and then implementing variations of patterns described in CSP with Go.

The book excels at keeping the density of information vs the pace of the book at a really consumable speed for your average developer. The strength of this books versus other sources on concurrency and concurrency with Go are that it really focuses on teaching the fundamental patterns with what’s going on under the hood; the lessons learned here are immediately applicable to Go programs, but even more so a skill that is transferrable to other languages, systems, and frameworks.

The weakest part of Learn Concurrent Programming with Go is the cartoon diagrams which I found difficult to follow and ended up largely ignoring.

Overall I’m super happy my purchase and would recommend this to Go developers early in their Go journey as it’s a great example of applying known concurrency patterns in Go, as well as experienced Gophers who want to brush up on their concurrency knowledge in a language they’re familiar with.
signposting character traits
Tags: gamedev, writing
Published: 2024-02-25 21:29:31

---
title: signposting character traits
published: true
date: 2024-02-22 00:00:00 UTC
tags: [ 'gamedev', 'writing' ]
canonical_url: https://onwriting.games/daily/20240222-928-signposting-character-traits/
---

Above many other things, the **consistency of actions and personality of our main character** is central to maintain the illusion of disbelief.

There is a very specific risk that we run in interactive fiction when we allow our character to have traits or when certain choices define their personality.

The problem lies in the fact that if this choice of personality or trait comes at a later stage in the game, the player may **a already have a preconceived notion** of how their character should act in different situations.

And when this doesn't happen, there is a moment of **disconnection and even displeasure**.

I'm sure you've experienced this a thousand times, not only in interactive fiction but also in books.

Luckily, the solution to this problem is practically the same: Signposting.

If we did a good job of "painting the picture" of who the character is up to a certain point and we have an option that adds depth to the personality (for example, choosing 1 out of 5 personality traits), the best thing we can do is write a signpost for each type of personality.

That is, write scenes or descriptions that help us make sense of the character's future actions thanks to their new personality or trait.

In this way, we include a transition stage between how the character behaved before, and how they should behave afterwards, improving our chances of not falling into actions that the player finds dissonant.
Dark Content Mode
Tags: css, webdev
Published: 2024-02-21 22:40:37

In case you haven't caught it yet, there's new functionality coming to browsers for dark mode applied to content. This could come as a surprise to web developers who did not plan for dark mode in their design, but is overall a win for those of us who prefer dark mode on all the things all the time.

It's already become my default on Android Edge, inheriting that I have my device in dark mode. I haven't found it to be default on any other browser (including desktop Edge). Chrome has it as an experiment features flag in chrome://flags, so I did most of my testing by enabling that.

## Issues Found

The biggest problem I found in my main work site was with images that were previously assuming white backgrounds. I found the nicest solution to that was using an SVG instead of a PNG file, which the dark content mode adapted to invert the colours quite nicely.

There were also some insufficient contrast I discovered, like grey borders around form text boxes, that were maybe a little weak in light mode but were barely visible in dark mode. Many of these were quickly solvable by making it a stronger contrast. For example, instead of a grey border against the white background, I made it into a black border. It content dark mode, it would flip to a white border on black background. Both modes came out looking better.

I identified a few other contrast elements that were not quite ideal. But attempting a similar approach did not work. There were a few variations where I had black against the default light theme and trying it with the dark content mode turned it into a grey instead of a white - far from invisible, but not as strong of a contrast as I wanted. This is a new feature, not enabled by default other than that Android Edge that few people use, so I'm hoping this gets cleaned up on the browser end and there isn't much else I need to do.

## No Way to Target?

I tried the media query for [prefers-color-scheme](https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-color-scheme) but it doesn't help for this. That detects if the device prefers dark mode, not if the browser's dark content mode is on. It's nice if you want to specifically define what everything should look like in dark vs light modes. But as far as I could find, there's no way to specifically target content dark mode at this time.
To Do List React
Tags: react, webdev, javascript, beginners
Published: 2024-02-21 23:53:54

**Introdução**
Desenvolvimento de um To Do List em React

**Aprendizado**
Criação de componentes, alinhamento, uso de métodos, trabalho com vários tipos de pesquisa e ordenação de dados.

**Execução**
Foi desenvolvido todo o app em react e finalizado.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8vjnaoizhyay27uk66pk.png)
The Story of Aksumite Platforms Part 2
Published: 2024-02-21 22:55:01

I am excited to code my first code Hello World but I didn't code that it is the default code for that code editor but is not different for me b/c I don't have anything about that by the way guess what is my first machine to code hello world.....?  it's a techno-pop2 Android cell phone... yeah it's a fan 😁 but I remember this gave me an amazing feeling I don't remember the date but I remember the year it was 2017 at that time I was graded 7 elementary students at Abunagrgoriyos Elementary and kindergarten school after that day I was thinking about what is code and what is the thing b/c that is new for me it just like a magic for me after that day I am falling in love with that magic blocks thing I promise my self to know that thing................to be continue
Hyper Scalable Chats-Push Protocol Updates
Published: 2024-02-21 22:38:45

## What's it?
Basically, web3 messaging which just got a massive upgrade!
On an overall, Push Chat makes messaging in web3 as seamless as it is in web2. One feature the Push Devs have been working on extensively within Push Chat is Push Group Chat, armed with the ability to host conversations with multiple members. Whether you're chatting in public groups, enjoying more private discussions, or joining token-gated communities, Push Group Chat makes connecting with others simple and secure.

## Scaling up means bringing it to a larger scale, innit?
 Push is levelling up its scalability and increasing group limits into the thousands.
Yeah, you read that correctly.

Group Chat platforms have always struggled with the number of participants a single group could accommodate. This limitation has hindered the potential for large-scale user interactions and hence restricted how Group Chats can be used to connect with a broader audience.

It's dubbed as to being "hyper scalable" in reference to Push Group Chat’s newfound ability to handle significantly larger group sizes, transcending its prior limitations, signifying a major development for web3-native user interactions , empowering users to engage in more extensive and inclusive group conversations like never before.

Push Group Chat has made a big change in how people can talk to each other in groups. Now, you can have more people in your public and private groups than ever before. Public groups can have up to 25,000 people, and private groups can have up to 5,000 people. That’s a lot of people! This means you can have more fun and more conversations with more people in web3.

## How is that possible?

Push Chat pioneers a decentralised approach, ensuring end-to-end encryption and placing control back into the hands of users, through transformational advancements at both the architectural and encryption levels. 
Before, the Push team was encrypting messages using the private keys of all group members. Now, they’re dynamically generating session keys and encrypted secrets after pivotal group state changes.
Text Underline Position
Tags: css, a11y
Published: 2024-02-21 22:43:20

This one is a quick accessibility CSS tip. I have long been a proponent of the old standard of underlining links, and never underlining anything else. It helps make it clear that it is a link. Add a hover and focus effect to make it more obvious when they are selecting it, too.

But it can introduce a problem: for certain reading disabilities, the line being close up against the text can make it hard to read. Even for myself without one of those disabilities, once it was flagged for me I immediately saw it every time I looked at a link.

So here's a quick CSS solution that significantly helps.

Use `text-underline-position: under` to make links with underlines easier to read. It moves the underline down to the bottom of the hanging letters (g, y, j) rather than right up tight against the bottom of other letters and cutting right through the middle of the hanging letters. It may not quite be perfect - even better might be a few pixels below the hanging letters to get space there as well - but it solves the majority of the problem with one quick CSS change.