Thursday, 24 November 2022

React Custom Hooks

 Hooks are reusable functions.

When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.

Custom Hooks start with "use". Example: useFetch.

Build a Hook

Suppose, we are fetching data in our Home component and displaying it. 

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

const Home = () => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((data) => setData(data));
 }, []);

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

The fetch logic may be needed in other components as well, so we will extract that into a custom Hook.

Move the fetch logic to a new file to be used as a custom Hook:

useFetch.js:

import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return [data];
};

export default useFetch;

Index.js

import ReactDOM from "react-dom/client";
import useFetch from "./useFetch";

const Home = () => {
  const [data] = useFetch("https://jsonplaceholder.typicode.com/todos");

  return (
    <>
      {data &&
        data.map((item) => {
          return <p key={item.id}>{item.title}</p>;
        })}
    </>
  );
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

We have created a new file called useFetch.js containing a function called useFetch which contains all of the logic needed to fetch our data.

We removed the hard-coded URL and replaced it with a url variable that can be passed to the custom Hook.

Lastly, we are returning our data from our Hook.

In index.js, we are importing our useFetch Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data from.

Now we can reuse this custom Hook in any component to fetch data from any URL.

Continue Reading →

useMemo Hook ReactJS

 The React useMemo Hook returns a memoized value.

  • Think of memoization as caching a value so that it does not need to be recalculated.

The useMemo Hook only runs when one of its dependencies update.

This can improve performance.

Performance

The useMemo Hook can be used to keep expensive, resource intensive functions from needlessly running.

for example, we have an expensive function that runs on every render. 

A poor performing function. The expensiveCalculation function runs on every render:

import { useState } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = expensiveCalculation(count);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
      <div>
        <h2>My Todos</h2>
        {todos.map((todo, index) => {
          return <p key={index}>{todo}</p>;
        })}
        <button onClick={addTodo}>Add Todo</button>
      </div>
      <hr />
      <div>
        Count: {count}
        <button onClick={increment}>+</button>
        <h2>Expensive Calculation</h2>
        {calculation}
      </div>
    </div>
  );
};

const expensiveCalculation = (num) => {
  console.log("Calculating...");
  for (let i = 0; i < 1000000000; i++) {
    num += 1;
  }
  return num;
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);

Use useMemo

To fix this performance issue, we can use the useMemo Hook to memoize the expensiveCalculation function. This will cause the function to only run when needed.

We can wrap the expensive function call with useMemo.

The useMemo Hook accepts a second parameter to declare dependencies. The expensive function will only run when its dependencies have changed.

In the following example, the expensive function will only run when count is changed and not when todo's are added.

import { useState, useMemo } from "react";
import ReactDOM from "react-dom/client";

const App = () => {
  const [count, setCount] = useState(0);
  const [todos, setTodos] = useState([]);
  const calculation = useMemo(() => expensiveCalculation(count), [count]);

  const increment = () => {
    setCount((c) => c + 1);
  };
  const addTodo = () => {
    setTodos((t) => [...t, "New Todo"]);
  };

  return (
    <div>
     ...
    </div>
  );
};

const expensiveCalculation = (num) => {
// Code goes here...
};

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);



Continue Reading →

useEffect hook in ReactJS

 useEffect(): It enables for performing the side effects in the functional components.

Some examples of side effects are: fetching data, directly updating the DOM, and timers.

useEffect accepts two arguments. The second argument is optional.

useEffect(<function>, <dependency>)

We should always include the second parameter which accepts an array. We can optionally pass dependencies to useEffect in this array.

1. No dependency passed:

useEffect(() => {
  //Runs on every render
});

2. An empty array:

useEffect(() => {
  //Runs only on the first render
}, []);

3. Props or state values:

useEffect(() => {
  //Runs on the first render
  //And any time any dependency value changes
}, [prop, state]);

Example Code: 

import Expenses from './component/expenses/Expenses';
import React,{useEffect, useState} from 'react';
import NewExpense from './component/newExpenses/NewExpense';

let _dummyExpense= [];

const App= ()=> {
    const [expenses, setExpense]= useState(_dummyExpense);

    function getExpenseData(){
        fetch('http://localhost:65257/API/Expense/').then(
            response=> {
                return response.json();
            }
        ).then(
            data=> {
                console.log(data);
                setExpense(data);
            }
        );
    }

    useEffect(()=> {getExpenseData();},[]);

    const addExpenseHandler= (expense)=>{
        fetch('http://localhost:65257/API/Expense/',{
            method:"Post",
            body:JSON.stringify(expense),
            headers:{'content-Type':'application/json'}
        }).then(
            response=> {
                getExpenseData();
            }
        );
    }

    return <div className="app-container">
        <h2>Parent App</h2>

        <NewExpense onAddExpense={addExpenseHandler}></NewExpense>
        <Expenses item={expenses}/>
    </div>
}

export default App;

Effect Cleanup

Some effects require cleanup to reduce memory leaks.

Timeouts, subscriptions, event listeners, and other effects that are no longer needed should be disposed.

Reference: https://reactjs.org/https://www.w3schools.com/

Continue Reading →

Saturday, 19 November 2022

React: Unidirectional data flow

 Unidirectional data flow is a technique that is mainly found in functional reactive programming. It is also known as one-way data flow, which means the data has one, and only one way to be transferred to other parts of the application. In essence, this means child components are not able to update the data that is coming from the parent component. In React, data coming from a parent is called props. Angular makes use of bi-directional binding in which the data flow takes place in both directions. React doesn’t support bi-directional binding to make sure you are following a clean data flow architecture. The major benefit of this approach is that data flows throughout your app in a single direction, giving you better control over it.

In terms of React it means:

  • state is passed to the view and to child components
  • actions are triggered by the view
  • actions can update the state
  • the state change is passed to the view and to child components

Note: The view is a result of the application state. State changes when actions happen. When actions happen, the state is updated.

One-way data binding provides us with some key advantages. Like:

  • Easier to debug, as we know what data is coming from where.
  • Less prone to errors, as we have more control over our data.
  • More efficient, as the library knows what the boundaries are of each part of the system.

In React, a state is always owned by one component. Any changes made by this state can only affect the components below it, i.e its children. Changing state on a component will never affect its parent or its siblings, only the children will be affected. This is the main reason that the state is often moved up in the component tree so that it can be shared between the components that need to access it.






Continue Reading →

Sunday, 13 November 2022

ES6 Spread Operator

The ES6 (ECMAScript 2015) spread operator is a powerful feature in JavaScript that allows you to expand or spread elements from an array or object into another array or object. It is represented by three consecutive dots (...). Here’s a breakdown of how it works and some common use cases:

1. Spreading Elements in Arrays

You can use the spread operator to spread elements of an existing array into a new array.

  const fruits = ['apple', 'banana', 'cherry'];
  const moreFruits = ['orange', ...fruits, 'mango'];
  console.log(moreFruits);
 
  // Output: ['orange', 'apple', 'banana', 'cherry', 'mango']

In this example, the ...fruits spreads out the elements of the fruits array into the moreFruits array.

2. Copying Arrays

The spread operator is often used to create a shallow copy of an array.

Example:

  const originalArray = [1, 2, 3];
  const copiedArray = [...originalArray];
  console.log(copiedArray);
 
  // Output: [1, 2, 3]

3. Spreading Elements in Function Calls

You can use the spread operator to pass elements of an array as individual arguments to a function.

Example:

  const numbers = [1, 2, 3];
  const sum = (a, b, c) => a + b + c;
  console.log(sum(...numbers));
 
  // Output: 6

Here, ...numbers spreads the array elements as individual arguments to the sum function.

4. Combining Arrays

You can use the spread operator to combine multiple arrays into one.

Example:

  const array1 = [1, 2];
  const array2 = [3, 4];
  const combinedArray = [...array1, ...array2];
  console.log(combinedArray);
  // Output: [1, 2, 3, 4]

5. Spreading Properties in Objects

The spread operator can also be used to spread properties from one object into another. This is especially useful for creating new objects based on existing ones.

Example:

  const person = { name: 'John', age: 30 };
  const job = { title: 'Developer', company: 'XYZ Corp' };
  const personWithJob = { ...person, ...job };
  console.log(personWithJob);
  // Output: { name: 'John', age: 30, title: 'Developer', company: 'XYZ Corp' }

6. Merging Objects

You can use the spread operator to merge objects, where properties from later objects will overwrite properties from earlier ones if they have the same key.

Example:

  const obj1 = { a: 1, b: 2 };
  const obj2 = { b: 3, c: 4 };
  const mergedObj = { ...obj1, ...obj2 };
  console.log(mergedObj); // Output: { a: 1, b: 3, c: 4 }

In this case, the value of b in obj2 overrides the value of b in obj1.

The spread operator is a versatile tool that simplifies many common programming tasks related to arrays and objects.


Continue Reading →

ES6 Modules

 Modules

JavaScript modules allow you to break up your code into separate files. This makes it easier to maintain the code-base.

ES Modules rely on the import and export statements.

Export

You can export a function or variable from any file.

Let us create a file named person.js, and fill it with the things we want to export.

There are two types of exports: Named and Default.

Named Exports

You can create named exports two ways. In-line individually, or all at once at the bottom.

//In-line individually:
//person.js

export const name = "Jesse"
export const age = 40

//All at once at the bottom:
//person.js

const name = "Jesse"
const age = 40

export { name, age }


Default Exports

Let us create another file, named message.js, and use it for demonstrating default export.

You can only have one default export in a file.

//message.js

const message = () => {
  const name = "Jesse";
  const age = 40;
  return name + ' is ' + age + 'years old.';
};

export default message;


Import

You can import modules into a file in two ways, based on if they are named exports or default exports.

Named exports must be destructured using curly braces. Default exports do not.

Import from named exports

Import named exports from the file person.js:

import { name, age } from "./person.js";

Import from default exports

Import a default export from the file message.js:

import message from "./message.js";


Continue Reading →

ES6 Destructuring

Destructuring in ES6 (ECMAScript 2015) is a feature that allows you to unpack values from arrays or properties from objects into distinct variables. It provides a more concise and readable way to extract data compared to traditional methods. Here's a breakdown of how destructuring works for arrays and objects:

Array Destructuring

Array destructuring allows you to extract values from an array and assign them to variables.

  const [a, b, c] = [1, 2, 3];
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // 3

Skipping Items: You can skip items in the array by leaving the position empty:

  const [first, , third] = [1, 2, 3];
  console.log(first); // 1
  console.log(third); // 3

Default Values: You can provide default values for variables:

  const [a = 1, b = 2] = [undefined, 3];
  console.log(a); // 1 (default value)
  console.log(b); // 3

Rest Operator: The rest operator (...) can be used to collect remaining elements into an array:

  const [first, ...rest] = [1, 2, 3, 4, 5];
  console.log(first); // 1
  console.log(rest);  // [2, 3, 4, 5]

Object Destructuring

Object destructuring allows you to extract properties from an object and assign them to variables.

  const { name, age } = { name: 'John', age: 30 };
  console.log(name); // John
  console.log(age);  // 30

Default Values: You can provide default values for variables:

  const { name = 'Anonymous', age = 25 } = { name: 'John' };
  console.log(name); // John
  console.log(age);  // 25 (default value)

Renaming Variables: You can rename variables while destructuring:

  const { name: userName, age: userAge } = { name: 'John', age: 30 };
  console.log(userName); // John
  console.log(userAge);  // 30

Nested Destructuring: You can destructure nested objects or arrays:

  const person = {
    name: 'John',
    address: {
      city: 'New York',
      zip: '10001'
    }
  };
 
  const { name, address: { city, zip } } = person;
  console.log(name); // John
  console.log(city); // New York
  console.log(zip);  // 10001

Rest Operator in Objects: The rest operator can also be used to collect remaining properties into a new object:

  const { name, ...rest } = { name: 'John', age: 30, city: 'New York' };
  console.log(name); // John
  console.log(rest); // { age: 30, city: 'New York' }

Destructuring can make your code more readable and reduce the need for repetitive property access or array indexing.

Continue Reading →

Saturday, 12 November 2022

React ES6

 What is ES6?

ES6 stands for ECMAScript 6.

ECMAScript was created to standardize JavaScript, and ES6 is the 6th version of ECMAScript, it was published in 2015, and is also known as ECMAScript 2015.

Why Should We Learn ES6?

React uses ES6, and you should be familiar with some of the new features like:

Continue Reading →

Thursday, 22 September 2022

React state and props

 React State

Every component in react has a built-in state object, which contains all the property values that belong to that component.

In other words, the state object controls the behaviour of a component. Any change in the property values of the state object leads to the re-rendering of the component.

Note- State object is not available in functional components but, we can use React Hooks to add state to a functional component.

How to declare a state object?

Example: 

    class Car extends React.Component{
            constructor(props){
               super(props);
               this.state = {
                brand: "BMW",
                color: "black"
          }
        }
    }

How to use and update the state object?

class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        brand: "BMW",
        color: "Black"
      };
    }
    changeColor() {
      this.setState(prevState => {
        return { color: "Red" };
      });
    }
    render() {
      return (
        <div>
          <button onClick={() => this.changeColor()}>Change Color</button>
          <p>{this.state.color}</p>
        </div>
      );
    }
    }

As one can see in the code above, we can use the state by calling this.state.propertyName and we can change the state object property using setState method.

React Props

Every React component accepts a single object argument called props (which stands for “properties”).  These props can be passed to a component using HTML attributes and the component accepts these props as an argument.

Using props, we can pass data from one component to another.

Passing props to a component:

While rendering a component, we can pass the props as an HTML attribute:

<Car brand="Mercedes"/>

The component receives the props:

In Class component:

class Car extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        brand: this.props.brand,
        color: "Black"
      };
    }
    }

In Functional component:

function Car(props) {
    let [brand, setBrand] = useState(props.brand);
}

Note- Props are read-only. They cannot be manipulated or changed inside a component

What are the differences between state and props?

 

State

Props

Use

Holds information about the

components

Allows to pass data from one component to other components as an argument

Mutability

Is mutable

Are immutable

Read-Only

Can be changed

Are read-only

Child components

Child components cannot access 

Child component can access

Stateless components

Cannot have state

Can have props


Continue Reading →

Virtual DOM in ReactJS

 Why was virtual DOM introduced? 

DOM manipulation is an integral part of any web application, but DOM manipulation is quite slow when compared to other operations in JavaScript. The efficiency of the application gets affected when several DOM manipulations are being done. Most JavaScript frameworks update the entire DOM even when a small part of the DOM changes.

For example, consider a list that is being rendered inside the DOM. If one of the items in the list changes, the entire list gets rendered again instead of just rendering the item that was changed/updated. This is called inefficient updating.

To address the problem of inefficient updating, the react team introduced the concept of virtual DOM.

How does it work?


For every DOM object, there is a corresponding virtual DOM object(copy), which has the same properties. The main difference between the real DOM object and the virtual DOM object is that any changes in the virtual DOM object will not reflect on the screen directly. Consider a virtual DOM object as a blueprint of the real DOM object. Whenever a JSX element gets rendered, every virtual DOM object gets updated.

**Note- One may think updating every virtual DOM object might be inefficient, but that’s not the case. Updating the virtual DOM is much faster than updating the real DOM since we are just updating the blueprint of the real DOM.

React uses two virtual DOMs to render the user interface. One of them is used to store the current state of the objects and the other to store the previous state of the objects. Whenever the virtual DOM gets updated, react compares the two virtual DOMs and gets to know about which virtual DOM objects were updated. After knowing which objects were updated, react renders only those objects inside the real DOM instead of rendering the complete real DOM. This way, with the use of virtual DOM, react solves the problem of inefficient updating.


Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (49) CD (1) CI (2) CloudComputing (2) Coding (8) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (19) Entity Framework (4) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives