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

 Spread Operator

The JavaScript spread operator (...) allows us to quickly copy all or part of an existing array or object into another array or object.

const numbersOne = [1, 2, 3];
const numbersTwo = [4, 5, 6];
const numbersCombined = [...numbersOne, ...numbersTwo];

The spread operator is often used in combination with destructuring.

Assign the first and second items from numbers to variables and put the rest in an array:

const numbers = [1, 2, 3, 4, 5, 6];
const [one, two, ...rest] = numbers;

We can use the spread operator with objects too:

Combine these two objects:

const myVehicle = {
    brand: 'Ford',
    model: 'Mustang',
    color: 'red'
  }
 
  const updateMyVehicle = {
    type: 'car',
    year: 2021,
    color: 'yellow'
  }
 
  const myUpdatedVehicle = {...myVehicle, ...updateMyVehicle}

Notice the properties that did not match were combined, but the property that did match, color, was overwritten by the last object that was passed, updateMyVehicle. The resulting color is now yellow.


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

 The Destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

With the syntax of destructuring, you can extract smaller fragments from objects and arrays. It can be used for assignments and declaration of a variable.

Assuming that you have a function that returns an array of numbers as follows:

function getScores() {
    return [70, 80, 90];
 }

let [x, y, z] = getScores();

console.log(x); // 70
console.log(y); // 80
console.log(z); // 90

The variables x, y and z will take the values of the first, second, and third elements of the returned array.

Note that the square brackets [] look like the array syntax but they are not.

If the getScores() function returns an array of two elements, the third variable will be undefined.

In case the getScores() function returns an array that has more than three elements, the remaining elements are discarded. 

Array Destructuring Assignment and Rest syntax

It’s possible to take all remaining elements of an array and put them in a new array by using the rest

syntax (...):

function getScores() {
    return [70, 80, 90, 100];
 }

 let [x, y ,...args] = getScores();
console.log(x); // 70
console.log(y); // 80
console.log(args); // [90, 100]

The variables x and y receive values of the first two elements of the returned array. And the args variable receives all the remaining arguments, which are the last two elements of the returned array.

let [name1, name2, ...rest] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

// rest is array of items, starting from the 3rd one
alert(rest[0]); // Consul
alert(rest[1]); // of the Roman Republic
alert(rest.length); // 2

The value of rest is the array of the remaining array elements.

We can use any other variable name in place of rest, just make sure it has three dots before it and goes last in the destructuring assignment.

Ignore elements using commas

Unwanted elements of the array can also be thrown away via an extra comma:

// second element is not needed
let [firstName, , title] = ["Julius", "Caesar", "Consul", "of the Roman Republic"];

alert( title ); // Consul

In the code above, the second element of the array is skipped, the third one is assigned to title, and the rest of the array items is also skipped (as there are no variables for them).

Default values

If the array is shorter than the list of variables at the left, there’ll be no errors. Absent values are considered undefined.

If we want a “default” value to replace the missing one, we can provide it using =:

// default values
let [name = "Guest", surname = "Anonymous"] = ["Julius"];

alert(name);    // Julius (from array)
alert(surname); // Anonymous (default used)



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 →

Topics

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

Dotnet Guru Archives