teleren/devto huggingface dataset:
How to use Hooks (useState and useEffect) in Reactjs
Tags: javascript, react, webdev, frontend
Published: 2022-12-28 14:18:37

React hooks are a powerful feature introduced in React 16.8 that allow you to use state and other React features without writing a class component. Hooks make it easier to reuse stateful logic and share it across your components, and they can make your code simpler and more expressive.

In this article, we'll look at how to use some of the most common React hooks, including useState, useEffect, and useContext. We'll also discuss some best practices and tips for using hooks effectively in your own projects.

**useState**
The useState hook is the most basic hook in React, and it allows you to add state to functional components. To use useState, you need to import it from the react package and call it inside your component. Here's an example of how to use useState to add a count to a component:


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

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
```
The first argument to useState is the initial state, and the second argument is a function that you can use to update the state. In this example, we're using an arrow function to increment the count by 1 every time the button is clicked.

useState returns an array with two elements: the current state value and a function to update it. You can use destructuring assignment to assign these values to separate variables, as we've done in the example above.

You can use useState multiple times to add multiple pieces of state to a component. For example, you might have a component with both a count and a name state variable:


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

function Example() {
  const [count, setCount] = useState(0);
  const [name, setName] = useState('Alice');

  return (
    <div>
      <p>Hello, {name}! You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
      <button onClick={() => setName('Bob')}>
        Change name
      </button>
    </div>
  );
}
```


**useEffect**
The useEffect hook is another important hook in React that allows you to perform side effects in functional components. Side effects are actions that have an impact outside of the component itself, such as making an HTTP request or interacting with the DOM.

To use useEffect, you need to import it from the react package and call it inside your component. Here's an example of how to use useEffect to fetch data from an API and update the component's state:


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

function Example() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function fetchData() {
      const response = await fetch('https://api.example.com/data');
```
Code Smell 189 - Not Sanitized Input
Tags: webdev, beginners, programming, security
Published: 2022-12-28 14:11:02

*Bad actors are there. We need to be very careful with their input.*

> TL;DR: Sanitize everything that comes from outside your control.

# Problems

- Security

# Solutions

1. Use sanitization and input filtering techniques.

# Context

Whenever you get input from an external resource, a security principle requests you to validate and check for potentially harmful inputs.

[SQL Injection](https://en.wikipedia.org/wiki/SQL_injection) is a notable example of a threat.

We can also add [assertions](https://dev.to/mcsee/code-smell-15-missed-preconditions-7c3) and invariants to our inputs.

Even better, we can work with [Domain Restricted Objects](https://dev.to/mcsee/code-smell-178-subsets-violation-1fkc).

# Sample Code

## Wrong

[Gist Url]: # (https://gist.github.com/mcsee/d72d1e6617755cd8eff723b4dba90078)
```python
user_input = "abc123!@#"
# This content might not be very safe if we expect just alphanumeric characters
```

## Right

[Gist Url]: # (https://gist.github.com/mcsee/2c19c64f268afb946ee8560e19cf444f)
```python
import re

def sanitize(string):
  # Remove any characters that are not letters or numbers
  sanitized_string = re.sub(r'[^a-zA-Z0-9]', '', string)
  
  return sanitized_string

user_input = "abc123!@#"
print(sanitize(user_input))  # Output: "abc123"

```

# Detection

[X] Semi-Automatic 

We can statically check all the inputs and also we can also use penetration testing tools.

# Tags

- Security

# Conclusion

We need to be very cautious with the inputs beyond our control.

# Relations

{% post https://dev.to/mcsee/code-smell-121-string-validations-38ph %}

{% post https://dev.to/mcsee/code-smell-178-subsets-violation-1fkc %}

{% post https://dev.to/mcsee/code-smell-15-missed-preconditions-7c3 %}

# More Info

- [Wikipedia](https://en.wikipedia.org/wiki/SQL_injection)

# Disclaimer

Code Smells are just my [opinion](https://dev.to/mcsee/i-wrote-more-than-90-articles-on-2021-here-is-what-i-learned-1n3a).

# Credits

Photo by [Jess Zoerb](https://unsplash.com/@jzoerb) on [Unsplash](https://unsplash.com/photos/UGCgoVmFZC0)
    
* * *

> Companies should make their own enterprise systems as often as network security companies should manufacture their own aspirin.

_Phil Simon_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}
Why Do SMEs Need CRM Software to Grow Their Businesses?
Tags: crm, crmsoftware, software
Published: 2022-12-28 14:10:03

An effective tool for managing customers throughout their lifecycle is a CRM system. For large businesses, it is essential, while SMEs are still deciding if they require CRM. A misunderstanding of the product may be to blame for the poor adoption of CRM in SMEs.

The first is that it is only for big businesses, and the second is that it is a pricey tool for small and medium-sized businesses. There are many others like them in the marketplace. These factors prevent SMEs from using the CRM system. Today, we'll talk about everything CRM-related and how they help businesses.

**What is CRM?**
A tool or technological system called CRM is used to manage business interactions with current and potential customers. CRM wants to make sure that businesses strengthen their connections with their clients. There are several processes involved in onboarding a new client, and if you don't have a well-organized procedure in place and miss one of them, it can not seem good when you subsequently contact your clients to apologize.

**How Does CRM Work?**
Understanding how CRM functions are essential before talking about how it might benefit SMEs. To begin with, it is crucial to understand all of the capabilities of CRM. As a result, once you decide to deploy a CRM system at your business, you need to identify the features that will work best for you and are unique to your industry (industry). Additionally, every business has a unique approach to dealing with clients. As a result, you must take that into account while choosing a CRM product.

The CRM process begins with the organization of customer information, which includes contact information, website information, information from social media, and anything else you can think of about your consumer.

Only a small number of SMEs now employ CRM software, according to the data that is available. In a recent study, it was discovered that 34% of SMEs do not have any plans to use it in the future.

**CRM Software is crucial for SMEs to Boost their Business**
1. Customer Relationship Management 

2. Increase efficiency 

3. Automate Sales tasks 

4. Integration with other software

5. Insights into sales performance 

6. Upselling opportunities 

7. Reports 

8. Team collaboration becomes easy 

9. Grievance Resolution 

CRM software can provide SMEs with a plethora of advantages. You should immediately think about investing in CRM [This post](https://www.qltech.com.au/hub/automate/why-is-crm-software-crucial-for-smes-to-boost-their-business/) will help you to grow your company or enhance the current processes.
How to reproduce hover effect on tags dev.to ?
Tags: webdev, beginners, css, modcss
Published: 2022-12-28 14:09:40

Today, while passing through the site, I noticed this effect that occurs when hovering over one of the site's tags (just below the article titles).
I wanted to try to reproduce this effect. I explain below how I did it :

## 1. Use html link with a href
These tags are hypertext links that's why you can click on them and be redirected elsewhere on the site.

```
<a href="https://dev.to/t/css">#css</a>
<a href="https://dev.to/t/beginners">#beginners</a>
<a href="https://dev.to/t/programming">#programming</a>
<a href="https://dev.to/t/modcss">#modcss</a>

```
---
## 2. Customize this

In this case, the links are decorated with invisible border, an padding, the text decoration (underline) has been disabled, a color has been applied to the text and a rounded edges effect.

**NB:** So, it's very important to add a thickness to the border beforehand even if it will be invisible. This avoids moving the other components when hovering over.

I use [MOD-CSS](https://mod-css.com/), a utility to quickly set style and manage states.

```
<a href="..." :box="tx.de[none] co[#202020] p[.5rem] br[6px] bd[1px solid transparent]">#css</a>
<a href="..." :box="tx.de[none] co[#202020] p[.5rem] br[6px] bd[1px solid transparent]">#beginners</a>
...

```

> **Meanings**
> _text-decoration: tx.de
> color: co
> border-radius: br
> padding: p
> border: bd_

---
## 3. Add hover effect
When hovered, the border reappears and the background is colored. Thus, we add a color of border and background.

```
<a href="//" :box="... && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#css</a>
<a href="//" :box="... && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#beginners</a>

```

> **Meanings**
> _&& hover : to set properties on hover state
> background : bg
> border-color: bd.co_

---
## 4. that's all !

**full code**

```
<a href="https://dev.to/t/css" :box="tx.de[none] co[#202020]
  p[.5rem] br[6px] bd[1px solid transparent] && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#css</a>

<a href="https://dev.to/t/beginners" :box="tx.de[none] co[#202020]
  p[.5rem] br[6px] bd[1px solid transparent] && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#beginners</a>

<a href="https://dev.to/t/programming" :box="tx.de[none] co[#202020] 
  p[.5rem] br[6px] bd[1px solid transparent] && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#programming</a>

<a href="https://dev.to/t/modcss" :box="tx.de[none] co[#202020]
  p[.5rem] br[6px] bd[1px solid transparent] && hover:bg[#e9a8a830] bd.co[#e9a8a8]">#modcss</a>

```

---
You can find snippet on [codepen](https://codepen.io/dev-geos/pen/ExpPpxg)
How to be productive without a 3 monitor aesthetic setup?
Tags: productivity, beginners, programming, tutorial
Published: 2022-12-28 14:05:39

Well, are you tired of watching Aesthetic 3-monitor, curve monitor setup which people use for work,coding or anything productive? Well here's what you can do instead.


1. Use keyboard shortcuts: Learning and using keyboard shortcuts can help you navigate and perform tasks more quickly and efficiently.

2. Use a productivity tool or app: There are many tools and apps available that can help you stay organized, track your progress, and manage your tasks.

3. Use multiple windows and tabs: If you don't have multiple monitors, you can still take advantage of multiple windows and tabs to keep your workflow organized.

4. Use a document or task management system: A document or task management system can help you keep track of your projects and tasks, and allow you to access your work from any device.

5. Use a timer: Set a timer to help you stay focused and on track. You can use a timer to break your work into shorter, more manageable blocks of time.

6. Take breaks: Don't be afraid to take breaks when you need them. Stepping away from your work for a few minutes can help you refocus and be more productive when you return.

7. Use a standing or treadmill desk: If you spend a lot of time at your desk, consider using a standing or treadmill desk to help reduce the risk of sedentary behaviours and improve your productivity.

8. Use a second screen: If you don't have multiple monitors, you can still use a second screen, such as a laptop, tablet, or smartphone, to help you stay organised and improve your productivity.

9. Use a headset or headphones: Using a headset or headphones can help you focus on your work and reduce distractions.

10. Optimize your work environment: Take steps to optimize your work environment to suit your needs and preferences. This may include adjusting your lighting, setting up a comfortable workstation, and reducing clutter and distractions.

![Spongebob on procastination](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/v8yk9m47z5jj2wg3kbm5.jpg)
Project Pilot - Short Notes
Tags: softwaredesign, programming
Published: 2022-12-28 13:51:26

Series on Software Design Practices – Part 3

In this small series on design practices, I write about various practices. In every article, I give a brief and simple explanation. In [part 2](https://claudioaltamura.de/architecture/short-notes-on-design-practices-pt-2-prototype) I wrote about prototypes. This time I present project pilots as another software development design practice.

We already talked about [spikes](https://claudioaltamura.de/architecture/short-notes-on-design-practices-pt1-spike-solutions), which help you to find approaches for a technical problem, or [prototypes](https://claudioaltamura.de/architecture/short-notes-on-design-practices-pt-2-prototype) to test a specific concept. What these concepts have in common is that they should not be used in production. Spikes may not be good enough or prototypes only focus on feasibility.

Right here comes in the so-called **project pilot**. You add additional points regarding production readiness, that you are able to test the viability and how likely it is that the software succeed. So it's the first phase in a larger project with a defined productive scope. And very importantly, project pilots provide you valuable feedback on ideas and concepts.

Project pilots are another good strategy for managing risk. The concept helps you to uncover potential flaws ahead of a full launch. Use this feedback to identify issues and correct them in advance.

Photo by [Benjamin Elliott](https://unsplash.com/@benjaminelliott?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/photos/gMb6mDSWUOU?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)
7 Ways of looping through an array in JavaScript.
Tags: webdev, javascript, programming, tutorial
Published: 2022-12-28 13:49:10

Simply put, an array is a collection of same data type items stored in contiguous(consecutive; following each other) memory locations.

More often than not, arrays are used during programming for a couple of reasons: storing user information, storing some identification attributes, just to mention but a few.

It becomes necessary at some point in time for a programmer to access this stored data and I have highlighted 7 ways in which one can easily do so using some JavaScript code snippets:

1. **<u>Looping through an array using for loop.</u>**

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

2. **<u>Looping through an array using while loop.</u>**

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

3. **<u>Looping through an array using do...while loop.</u>**

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

4. **<u>Looping through an array using map() method.</u>**

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

5. **<u>Looping through an array using for...of.</u>**

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

6. **<u>Looping through an array using for...in.</u>**

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

7. **<u>Looping through an array using forEach() method.</u>**

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

I hope the article was helpful. Happy coding!
New React Learner!
Tags: react, beginners, question
Published: 2022-12-28 13:49:00

Hi DEV Community 👋

Making my first post here, and instead of just saying hi, I thought I would ask a question.. 

> As a new learner, is learning class components (vs functional components) a waste of time? 

I am using Codecademy as my learning platform - I worked through what I now realise is an older course using classes but found them quite nice to conceptualise and understand. I've moved on to functional components and hooks but I miss using the classes. This feels like an unpopular opinion. 

Where do you guys stand on classes vs functions and hooks, going into 2023, especially for a new developer?
React useEffect only on Update
Tags: javascript, react, reactnative, typescript
Published: 2022-12-28 13:35:42

Have you ever thought what is the best way to run Redact’s useEffect Hook only on updates? Have you ever considered Redact’s useRef Hook as a solution to create an instance variable and track the lifecycle of a component?

We can define a ref variable in the functional component in React when It is necessary to keep tracking some state without using React’s re-render mechanism.  illustration, we can determine if a component was rendered for the first time or if it was re-rendered. First, consider the following example:

```javascript
const UseEffectUpdates = () => {

    const[ txtValue, setTxtValue] = useState({
        value1:"",
        value2:""
    })
    const [txtColor, setTxtColor] = useState("white");

    const [toggle, setToggle] = useState(true);
    const didMount = useRef(false);
    const handleToggle = () => {
        setToggle(!toggle);
    };

    const txtChange1 = (event)=>{
        event.preventDefault();
        console.log("textbox change 1");
        setTxtValue({...txtValue, value1:event.target.value});
        if (txtValue.value2 ===  event.target.value){
            setTxtColor("green");
        }
    }

    const txtChange2 = (event)=>{
        event.preventDefault();
        console.log("textbox change 2");
        setTxtValue({...txtValue, value2:event.target.value})
        if(txtValue.value1 === event.target.value){
            setTxtColor("green")
        }
    }

    useEffect(() => {
        if (didMount.current) {
        console.log('I run only if toggle changes.');
        } else {
        didMount.current = true;
        }
    }, [toggle]);

    return (
        <div>
            <input style={{backgroundColor:txtColor}} type="text"  placeholder="name1" onChange={txtChange1}  value={txtValue.value1}/>
            <br/>
            <input style={{backgroundColor:txtColor}} type="text"  placeholder="name2" onChange={txtChange2}  value={txtValue.value2}/>
            <br/>
            <button type="button" onClick={handleToggle}>
                Toggle
            </button>        
        </div>
    );
};

```
In the above sample code, the didMount variable is initialized with true, because it is supposed to be the component rendered the first time when it gets initialized. Also using the useEffect hook with toggle dependency to update the ref’s current property(didMount) after the first render of the component. When the didMount is false, it doesn’t trigger a re-render thought.When you run the above code, the useEffect just runs when clicking on the toggle button, and the handleToggle event runs. On the other hand, when the textboxes are changed the useEffect doesn’t run.

That is all. If you want to keep track of the state in your React component which shouldn't cause it to re-render, React's useRef Hooks is an option to create an instance variable for it.
Estrutura do NestJS
Tags: javascript, node, nestjs
Published: 2022-12-28 13:26:11

NestJS é um framwork NodeJS opnitativo, ou seja, segue uma estrutura bem definida. Esse artigo mostra a teoria necessária para construir e manter aplicações com essa tecnologia para iniciantes no assunto. 

## Pacotes usados no NestJS
Alguns dos pacotes mais importantes do NestJS são:

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

Além dos pacotes acima que são os mais básicos e estarão em praticamente qualquer aplicação, o nest possui diversos outros pacotes que ajudam a integrar o nest com o [typeorm](https://docs.nestjs.com/recipes/sql-typeorm) ou [swagger](https://docs.nestjs.com/openapi/introduction) por exemplo.

### Request lifecycle
O Nest possui blocos para executar as tarefas comuns de uma api. A validação dos dados, por exemplo, é feita por pipes e a autenticação por guards. No diagrama abaixo é possível ver o [ciclo de vida de um requisição](https://docs.nestjs.com/faq/request-lifecycle) de modo que é possível ver a ordem cronológica até a requisição ser processada e enviada como resposta.

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

### Módulos
Faz o encapsulamento de código e dos blocos mostrados acima (controllers, services, guards ...) para um único propósito. Pode haver um módulo de users e de products por exemplo. Cada aplicação deve ter pelo menos um módulo root chamado app module.

- providers
- controller
- imports
- exports
1962. Leetcode Solution in Javascript
Tags: javascript
Published: 2022-12-28 13:24:01

```javascript
/**
 * @param {number[]} piles
 * @param {number} k
 * @return {number}
 */
var minStoneSum = function(piles, k) {
    const heap = new Heap(piles);
    
    let i = 0;
    while(i< k){
	
		//TAKE THE TOP MAX VALUE TO REDUCE
        let top = heap.dequeue();
        let updated = top - (~~(top/2));
		
		//IF AFTER  UPDATION VALUE IS NOT 0 THEN INSERT AGAIN
        if(updated){
            heap.enqueue(updated);
        }
        i++;
    }
    return  heap.getTree().reduce((acc,v)=> acc+v,0);
    
};


class Heap{
    constructor(list = []){
        this.tree = [null];
        this.list = list;
        this.build();
    }
    
    build(){
        for(let priority of this.list)
            this.enqueue(priority);
    }
    
    swap(pos1, pos2){
        [this.tree[pos1], this.tree[pos2]] = [this.tree[pos2],this.tree[pos1]]
    }
    
    enqueue(priority){
        this.tree[this.tree.length] = priority;
        let i = this.tree.length - 1, parent = ~~(i/2);
        while(i > 1){
            if(this.tree[parent] < this.tree[i])
                this.swap(parent,i);
            i = parent;
            parent = ~~(i/2);
        }
    }
    
    dequeue(){
     let size = this.tree.length - 1, pos = 1;
    if(!size) return;


    let last = this.tree.pop(), deleted = this.tree[pos];


    if(!deleted && last) return last;

    this.tree[pos] = last;
    this.heapify(pos);
    return deleted;
    }
    
    heapify(pos){
    
        if(pos > this.tree.length) return;
        let leftPos = 2*pos, rightPos = 2*pos +1;
        
        let left = this.tree[leftPos] ? this.tree[leftPos] : -Infinity;
        let right = this.tree[rightPos] ? this.tree[rightPos] : -Infinity, minVal = null, minIndex = null;
        
        if(left > right){
            minVal = left;
            minIndex = leftPos;
        }else{
            minVal = right;
            minIndex = rightPos
        }
        if(this.tree[pos] < minVal){
            this.swap(pos,minIndex);
            this.heapify(minIndex);
        }
        
    }
    
    getTree(){
        return this.tree.slice(1);
    }
    
    getSize(){
        return this.tree.length - 1;
    }
}
```
#leetcode
#challenge
Here is the link for the problem:
https://leetcode.com/problems/remove-stones-to-minimize-the-total/