teleren/devto huggingface dataset:
Proper structure of a react application
Tags: react, webdev, structuring, development
Published: 2023-06-05 19:38:52

Hello there,I am Muhire Ighor a react developer ,In this blog I will be talking about the proper structuring of a react application .
Many people often face a problem of poor structuring of their react application code base.
I have summarized this structure into about 7 main parts:
**Pages**,**Components**,**hooks**,**utils**,**layouts**,**data**,**context**,**styles**,**assets**



As of the current version of react **18.2**
Every project is mainly wrapped in the src folder:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qcysrgqn66hp9bfaoail.png)
Above is the attached general react file structure

## **Pages**
In the pages folder this is where you put the final page to be displayed in the browser on a certain endpoint:
For example one may say a Home page at "localhost:3000"

## **Components**
Then in the home page he/she may have the Navbar component ,then 
the Navbar component will go into the Components folder for allowing re usability across the application 🤪🤪.

## **Layout**
We may have like the Auth layout where as both the signup and signin may all have a footer so there is no use for repetition we can make an AuthLayout in the layout folder where by the use of the **outlet component** from the "react-router-dom" ,the outlet component allows us to have various page views but with some common components according to the routes that is specified in the routing file as for my example:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n821jm6nlb78bjo3u6lf.png)
You can observe that we have the HomeLayout component that is to accept a specific child according to the route where like for the main end point "/",
we will have the MainComponent for the "/" endpoint,
Contacts for the "/pages/contact" end point,
and the Aboutus component for the "/pages/discover..." and then the Notfoundpage component for any of the routes that is not specified.

## **Hooks**
In the **hooks** section we put there some custom functions that will be used in many of our components but using different arguments.
In this section it is advisable to begin your function using the "**use**"keyword eg:"useSignup"

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lb86trkozbxl2rip3ruz.png)

## **Styles**
In the **Styles** folder one puts his/her css stylings .

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ixk79r0ljs29d4dkkpab.png)

## **data**
In the data folder one may put the dummy data to be used in case he/she has not got active backend from which to fetch the data from.

## **Utils**
In the **utils** folder we put there some functions to operate on some inputs like for my example I made a cash formatting function to format the currency for the products added on the cart.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/j29mpfxpq38je8m0fa6j.png)
Unlock the Power of JavaScript Immutability: Predictable Development!
Tags: javascript, webdev, programming, redux
Published: 2023-06-05 19:00:58

JavaScript, the dynamic programming language that powers the web, continues to evolve with exciting new features.

From enhanced syntax and improved performance to advanced functionalities, these updates unlock a world of possibilities for developers. 

Get ready to embrace the latest innovations and take your JavaScript coding to the next level.

# Immutability
-> Immutability in JavaScript refers to the concept of creating and working with data structures that cannot be modified once they are created. **Instead of directly modifying existing data, immutable programming promotes creating new copies with the desired changes.**

In JavaScript, **primitive values (like numbers and strings) are immutable by default,** meaning their values cannot be changed once assigned.

**Some techniques to achieve immutability**

**1. Object spread syntax:** Create a new object by spreading the properties of an existing object and adding or overriding specific properties.

```
const originalObject = { a: 1, b: 2 };
const newObject = { ...originalObject, c: 3 };
```
Only makes immutable to the number of degrees you spread the object.


**2. Array methods: **Use array methods like concat(), slice(), and map() to create new arrays based on existing ones, instead of directly modifying them.

```
const originalArray = [1, 2, 3];
const newArray = originalArray.concat(4);
```

**3. Object.assign():** Merge objects together by using Object.assign() to create a new object, rather than modifying the original objects.

```
const obj1 = { a: 1 };
const obj2 = { b: 2 };
const mergedObject = Object.assign({}, obj1, obj2);
```

Now we also have with, toSorted and toRevese (relatively new and not supported on all browsers)

**4. StructuredClone (aka deep copy)**
-> The purpose of a StructuredClone function is typically to create a deep copy of an object or array in a structured manner, preserving the original data's structure and references.

for example

```
const original = {
  name: "John",
  age: 30,
  hobbies: ["reading", "coding"],
  address: {
    street: "123 Main St",
    city: "New York"
  }
};

const duplicate = structuredClone(original)

// now duplicate is a deeply copied object which has 
a brand new memory reference.
```


Hope this was a good read. Will also bring new css feature in next blog. Please check out the below package.


# Extras

** I also have a new package for generating results from incoming api responses. If your backend devs send you multiple api's to fetch from this package helps you **

{% embed https://www.npmjs.com/package/jx-response-generator %}
We started to approach code reviews as engineering tasks. We're merging now faster than ever
Published: 2023-06-05 19:00:43

In the fast-paced world of software development, effective code reviews and seamless management of merge requests (MRs) play a crucial role in ensuring smooth collaboration and timely delivery. However, many teams struggle with bottlenecks, delays, and the risk of MRs getting lost in the shuffle. In this article, we will explore a practical approach to address these challenges and optimize the code review process, leading to improved team efficiency and streamlined collaboration.

As a team manager overseeing a group of talented developers, I have encountered firsthand the common pain points associated with code reviews and MR management. 

With a team size of approximately six developers and a broader organization comprising around 200 developers, it became evident that our existing approach was falling short.

The traditional method involved throwing MRs into the team's communication channel, resulting in the need to constantly ping team members for reviews. This approach proved to be suboptimal, with developers often experiencing unnecessary delays, and MRs occasionally being forgotten or overlooked.

**Experimenting with a New Approach**

To address these challenges, we embarked on an experiment to integrate code reviews seamlessly into our daily workflow. During our daily standup meetings, we started assigning unreviewed MRs to each team member based on relevancy, code ownership, and availability. This approach aimed to make code reviews an integral part of our daily routine, ensuring that reviews were completed in a timely manner and reducing the need for continuous follow-ups and pings among team members.

**The Results and Benefits**

The implementation of our new approach yielded promising results. Developers were more proactive in completing their assigned reviews, taking ownership of their time slots and allocating dedicated periods for code reviews. This proactive mindset not only expedited the review process but also reduced the effort required to coordinate and ping other team members for reviews. The overall impact was a significant reduction in the time it took to merge code, enhanced collaboration, and increased team productivity.

**Seeking Further Insights**

While our new approach has shown considerable success, we believe in the power of shared knowledge and continuous improvement. We invite fellow engineering managers and developers to share their experiences and provide additional insights into reducing code merge time and improving collaboration. By fostering a community of learning and collaboration, we can collectively refine our practices and optimize the code review process.
React's arrow of Reconciliation
Tags: webdev, javascript, programming, react
Published: 2023-06-05 18:50:43

In React, reconciliation is the process of comparing the virtual representation of a component's previous state with its new state, and determining the minimal set of changes needed to update the user interface efficiently. It's how React figures out what parts of the UI need to be updated when the state or props of a component change.

Here's a step-by-step explanation of the reconciliation process in React:

1. Virtual DOM: React uses a virtual representation of the DOM called the Virtual DOM. It's a lightweight copy of the actual DOM.

2. Render: When a component's state or props change, React re-renders the component and generates a new virtual representation of the component's UI.

3. Diffing: React takes the previous virtual representation (from the previous render) and the new virtual representation (from the current render) and performs a process called "diffing." Diffing involves comparing the two representations and identifying the differences between them.

4. Update Strategy: React employs an efficient update strategy based on the diffing process. It aims to minimize the number of actual changes made to the real DOM by only applying the necessary updates.

5. Reconciliation: Once React has identified the differences between the previous and new virtual representations, it performs the necessary updates to the real DOM to reflect the changes. This process is called reconciliation.

During reconciliation, React follows a few principles to optimize the update process:

- Elements of different types are considered different and are completely rebuilt from scratch.
- React tries to update the props of components if they have the same type.
- React uses a "key" prop on lists of elements to improve the efficiency of updates.

By following these principles, React ensures that the user interface remains in sync with the component's state and props while minimizing unnecessary DOM manipulations, resulting in better performance.

Reconciliation is a core concept in React, but you don't need to worry about it too much in your day-to-day development. React's reconciliation algorithm is highly optimized and handles most cases efficiently. However, understanding the basics of reconciliation can help you write more efficient and optimized React components when dealing with larger applications.
Server State vs Client State in React for Beginners
Tags: react, webdev, javascript, beginners
Published: 2023-06-05 18:43:40

In React, managing state is a crucial aspect of building efficient and scalable applications. Two types of state exist in React applications: server state and client state. In this article, we will discuss the differences between these two types of state, their use cases, and how to manage them effectively.


## Server State

Server state refers to the data fetched from an API or a backend server. This data is not yet processed or manipulated by the client-side code. When working with server state, it is essential to handle asynchronous data fetching and caching to ensure a smooth user experience.

[TanStack Query](https://tanstack.com/query/v3/) (formerly React Query) is a popular library for managing server state in React applications. It is efficient and makes the UI smooth on the client side. With TanStack Query, components will only re-render when the data that they need has been fetched. 

Here's an example of using TanStack Query to fetch data from a server:

```
import { useQuery } from 'react-query';

const fetchPosts = async () => {
  const response = await fetch('https://api.example.com/posts');
  return response.json();
};

const Posts = () => {
  const { data, isLoading, error } = useQuery('posts', fetchPosts);

  if (isLoading) return <div>Loading...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {data.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
};

```

## Client State
Client state refers to the data that is specific to the client-side and is not dependent on server data. This includes UI state, form data, and other ephemeral information.

In React, you can manage client state using built-in hooks like useState and useReducer, or use state management libraries like Redux.

**Tip for Intermediate Developers:** Try and Explore [Zustand](https://zustand-demo.pmnd.rs/)

Here's an simple most example of managing client state using the useState hook:

```
import React, { useState } from 'react';

const Counter = () => {
  const [count, setCount] = useState(0);

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

  return (
    <div>
      <button onClick={handleClick}>Increment counter</button>
      <div>Counter value: {count}</div>
    </div>
  );
};

```

## Conclusion
Managing server state and client state in React applications is essential for building efficient and scalable applications. TanStack Query is a popular library for managing server state, while built-in hooks like useState and useReducer can be used for managing client state.

By understanding the differences between server state and client state, you can effectively manage your application's state and provide a seamless user experience.
What's your initial reaction to Apple Vision Pro?
Tags: ios, watercooler, discuss, apple
Published: 2023-06-05 18:37:30

Apple just launched their AR/VR headset called Apple Vision Pro.

{% embed https://www.theverge.com/2023/6/5/23738968/apple-vision-pro-ar-headset-features-specs-price-release-date-wwdc-2023 %}

Do you have any initial reactions?
Apple's New Announcement at WWDC23
Tags: discuss, news
Published: 2023-06-05 18:35:43

### The new Apple WWDC23 Announcement:

### Vision Pro
- You can control content with your eyes, hands and voice using the Vision Pro
- Over 100 Apple Arcade games on Vision Pro
- Separate battery pack of the Apple Vision Pro.
- FaceTime on Vision Pro
- Vision Pro features two 4K micro OLED displays and dual drivers with Spatial Audio
- The Vision Pro runs on two chips: M2 and R1

### iOS 17
- Apple introduces Standby in iOS 17
- You no longer have to say "Hey Siri" in iOS 17
- Apple introduces the Journal app in iOS 17
- You can now leave FaceTime video messages in iOS 17
- New customizable call screens in iOS 17
- Live voicemail in iOS 17
- The first beta of iOS 17 will be available in a few hours

### macOS Sonoma
- Apple intoduces macOS Sonoma
- You can now add widgets to your desktop in macOS Sonoma

### iPadOS 17
- Apple brings the customizable Lock Screen to iPadOS 17
- Apple introduces interactive widgets in iPadOS 17

### Other
- Apple introduces NameDrop, a new way to share contact information when two devices are brought together
- The new Mac Pro
- Apple introduces M2 Ultra
- Apple introduces the 15" MacBook Air


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gwz2uh3zykcl5jliab29.png)

---

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ogx3ecaoo1lqy6kh6kqi.png)

---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qzwy8ecwvyx9uaqhlhfz.png)

---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jjsjsrncwocjmejm0fqd.png)

---
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/apylaqnot4k76idx9f7z.png)
Stream Replication: The Perfect Sync Dance in the PostgreSQL Orchestra
Published: 2023-06-05 18:03:02


## Introduction:
In the captivating symphony of PostgreSQL, where various components harmonize to create a masterful database performance, stream replication takes center stage as the conductor of perfect synchronization. In this enlightening blog post, we explore how stream replication elegantly intertwines with other key components of PostgreSQL, forming a seamless ensemble that delivers remarkable data consistency and availability.

## Chapter 1: Stream Replication and the Buffer Manager Ballet
In the dance of database synchronization, stream replication gracefully partners with the Buffer Manager. While stream replication ensures that replicas stay in sync with the master, the Buffer Manager steps in as a nimble dancer, caching frequently accessed data in memory. Together, they create a dynamic duo, reducing disk I/O and enhancing overall performance. With each step, they minimize latency, ensuring that the music of data flows effortlessly across the PostgreSQL stage.

## Chapter 2: WAL and Stream Replication: A Tango of Transactional Mastery
As stream replication takes the lead, the Write-Ahead Logging (WAL) mechanism joins the dance floor, performing a passionate tango of transactional mastery. WAL captures every change made to the database, creating a log that stream replication utilizes to keep replicas in perfect rhythm with the master. Together, they ensure that no data alteration goes unnoticed, orchestrating a symphony of consistency and reliability.

## Chapter 3: Locking and Concurrency: A Waltz of Synchronized Access
In the world of concurrency, stream replication engages in a graceful waltz with PostgreSQL's locking and concurrency control mechanisms. As multiple users perform their dance of queries and updates, stream replication ensures that replicas maintain synchronized access to data. With careful coordination and synchronization steps, they prevent conflicts and maintain data integrity, ensuring a flawless performance on the PostgreSQL stage.

## Chapter 4: The Chorus of High Availability and Load Balancing
Stream replication harmonizes with other components to bring the chorus of high availability and load balancing. Combining the power of synchronous or asynchronous replication, load balancers distribute the workload across replicas, providing fault tolerance and scaling capabilities. This collaborative performance guarantees uninterrupted availability and an optimized database environment that can handle the crescendo of user demands.
What is control flow based narrowing in TypeScript?
Tags: webdev, javascript, typescript, beginners
Published: 2023-06-05 17:44:33

**Control flow based narrowing** refers to a type inference technique that allows the TypeScript compiler to narrow down the type of a variable based on the analysis of its control flow within conditional statements (such as `if` statements and `switch` statements).
<!--more-->
When TypeScript analyzes the control flow of a program, it can determine certain conditions that guarantee the state of a variable. This analysis helps TypeScript to infer a more specific type for that variable within the respective branch of the control flow.

Consider the following TypeScript code snippet:

```ts
function processValue(value: string | number) {
  if (typeof value === "string") {
    // TypeScript knows here that `value` is of type `string`
    console.log(value.toUpperCase());
  } else {
    // TypeScript knows here that `value` is of type `number`
    console.log(value.toFixed(2));
  }
}
```

In this example, TypeScript uses **control flow based narrowing** to determine that within the `if` block, the variable `value` is a `string`. Conversely, in the `else` block, it knows that `value` is a `number`. 

This enables the compiler to provide more accurate type checking and enables developers to use the appropriate properties or methods specific to each type without explicit type assertions.

Control flow based narrowing is a powerful feature of TypeScript that enhances type safety and helps catch potential errors at compile-time by providing more precise type information based on the analysis of control flow within the code.

## Control Flow Based Type Analysis

This video tutorial demonstrates control flow based narrowing:

{% youtube MBmFvFVrtGk?t=135 %}

## Interested in learning more? 🎓

I've spent years working with the TypeScript programming language and have encountered its various challenges. That's why I've recorded a series of [**free TypeScript video tutorials**](https://www.youtube.com/playlist?list=PLCbdBdyNHZXL3grXeUPZwTn1lo7pVaUdH), designed to help you enhancing your coding skills. 

I invite you to take a look at them and provide your feedback on the videos. I'm eager to hear your thoughts and impressions. 👀
Understanding Promises in JS
Tags: javascript, beginners
Published: 2023-06-05 17:42:24

## What are Promises?
Promises are a way of handling asynchronous code in JavaScript. Asynchronous code is code that runs in the background and doesn't return until it's finished. This can be things like loading a web page, fetching data from a database, or making an API call.

Promises let you write code that's more organised and easier to read. They also make it easier to handle errors.

## How do Promises Work?
A promise is an object that represents the eventual completion or failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected.

- When a promise is pending, it hasn't finished yet.
- When a promise is fulfilled, it has finished successfully.
- When a promise is rejected, it has finished unsuccessfully.

You can create a promise using the `new Promise()` constructor. The constructor takes a function as its argument. This function is called the promise's resolver. The resolver function is responsible for setting the promise's state to fulfilled or rejected.

Lets understand the promise by the following example:

```
const promise = new Promise((resolve, reject) => {
  // Do something asynchronous here.
  // After the execution is finished, call `resolve()` or `reject()`.
});
```

## How to Use Promises?

Once you have a promise, you can use it to do things like:

- Wait for the asynchronous operation to finish.
- Check the status of the asynchronous operation.
- Handle errors that occur during the asynchronous operation.

To wait for the asynchronous operation to finish, you can use the `then()` method. The `then()` method takes two functions as its arguments. The first function is called when the promise is fulfilled. The second function is called when the promise is rejected.

Here's an example of how to use the `then()` and `catch()` method:

```
// Resolve a promise with a value
const promise1 = new Promise((resolve, reject) => {
  resolve('Hello, world!!');
});

promise1.then(value => console.log(value)); 
// logs "Hello, world!!"

// Reject a promise with an error
const promise2 = new Promise((resolve, reject) => {
  reject(new Error('Something went wrong'));
});

promise2.catch(error => console.log(error)); 
// logs "Something went wrong"


```

## Conclusion
Promises are a powerful tool for handling asynchronous code in JavaScript. They make your code more organised and easier to read. They also make it easier to handle errors.

If you're new to promises, I encourage you to learn more about them. There are many resources available online, including tutorials, articles, and blog posts.

I hope this blog post has helped you understand promises.
Tailwind isn't working on my Typescript React
Tags: help, webdev, react, tailwindcss
Published: 2023-06-05 17:40:00

I installed tailwind css, with craco for my react app (following tailwind docs) but it's results doesn't show on my browser. Please help out on what I can do.


![Results image](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/79jamrw5l2m4thfilf72.png)


![Error Img](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/18jwxt3dq3yn8ylgixas.png)


![Image of error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jkfcmlszvofkynoydft8.png)

![Image of error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tymchzvfi86wxus9ac30.png)

![Image of error message](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/juflcxm8bj0g353zjf1r.png)