Little about react
Published: 2022-01-31 06:18:57

ProtoTypes
PropTypes provides a set of validators for ensuring that the data you get is correct. PropTypes.string is used in this example. A warning will appear in the JavaScript console if an incorrect value is given for a prop. propTypes is only tested in development mode for performance reasons. For using ProtoTypes you need to install it with npm i proto-types .

```
import { PropTypes } from "prop-types";
import React from "react";
 
 
class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
 
Greeting.propTypes = {
  name: PropTy
```
State-props
State and props both hold information and that information renders the output. They are different in one point. 

Props are like arguments to a function. Where the state is managed the component. In other words it is like the variable that we declared within a function.

JSX
JSX stands for JavaScript Syntax Extension. JSX helps us to write HTML tags in JavaScript and it helps developers to understand what they are writing and how it's gonna look like. Basically jsx is used with react.

```
import React from 'react';
 
const test = () => {
    return (
        <div>
           //this div is a jsx extension. Not a HTML tag
        </div>
    );
};
 
export default test;
```
Component Lifecycle. 
React web apps, as we've seen, are basically a collection of discrete components that execute in response to user events. Every React Component has its own lifecycle, which can be defined as a collection of functions that are called at various phases of the component's existence. The term is simple, but what do we mean when we say "various stages"? A React Component can go through the following four stages throughout its existence.

Initialization: The component is built with the specified Props and default state at this step. This is done in a Component Class's constructor.

Mounting: The step of rendering the JSX returned by the render function is known as mounting.

Updating: When the state of a component is modified and the application is repainted, this is referred to as updating.

Unmounting: As the name implies, Unmounting is the last phase in the component lifecycle, and it involves removing the component off the page.


Hooks
React hooks are nothing but JavaScript functions. You can use hooks in new components without rewriting the existing code. When you are using hooks you need to remember two things. 
Import the hook at top of your code and don’t use it inside loops, nested functions or conditions.
Don’t call hooks from javaScript functions. Call it from react functional components. But you can call your own custom hook like javaScript functions. There are some hooks that we use in our react application.Like, useState, useEffect, useReducer, useRef, useMemo etc.

useState hook
The state is updated using the setState function. It receives a new state value and re-renders the component in the background.

useEffect hook
After the render is committed to the screen, the function supplied to useEffect will be called. Consider effects as a way to go out of React's completely functional world and into the imperative one.

Effects are fired after each finished render by default, but you may opt to have them fire only when specified variables have changed.

useReducer hook
When you have sophisticated state logic including several sub-values or when the future state is dependent on the prior one, useReducer is typically preferred over useState. Because you may pass dispatch down instead of callbacks, useReducer can help you improve performance for components that trigger deep modifications.

useRef hook
UseRef is essentially a "box" that may contain a modified value in its.current property.

useMemo hook
When one of the dependencies changes, useMemo will merely recompute the memoized value. This optimization aids in the avoidance of costly calculations on each render.

Keep in mind that the function supplied to useMemo is called while the page is being rendered.




Custom hook

Custom hooks are nothing but javaScript functions. We always have some common functions that we use in multiple components which makes the code a little bit disorganized and it's hard to maintain. But custom hooks make our life easier. For example you need to save some data to your Local Storage so, all you need to do just write a function and export it. Just like the code below.

```
import { useState } from " react";
 
export default function useLocalStorage(parameter) {
  const [value, setValue] = useState(parameter);
  return [value, setValue];
```
Now, wherever you want to use it, just import it and use it.


Context Api
Generally we pass from one component to another through prop drilling. But it creates some problems when you pass data from one parent component to another parent component or from a child or super Child 

```
import React, { createContext } from "react";
import useFirebase from "../../hooks/useFirebase";
 
export const AuthContext = createContext(null);
 
const AuthProvider = ({ children }) => {
  const allContexts = useFirebase();
  return (
    <AuthContext.Provider value={allContexts}>{children}</AuthContext.Provider>
  );
};
 
export default AuthProvider;
```
Virtual DOM and diffing- algorithm

The virtual DOM is a programming concept in which a library like ReactDOM keeps an ideal, or "virtual," version of a user interface in memory and syncs it with the actual DOM. This is referred to as reconciliation.

React analyzes both the actual DOM tree and its own equivalent replica — the virtual DOM — whenever you edit a node on a DOM tree until it discovers a diverging node. React travels to the actual DOM and changes the node that was modified in the virtual DOM when it "sees" that the updated node in question does not match the actual node.

React compares the old DOM to the new using a mechanism called the diffing algorithm, according to its publicly available documentation. Diffing is a heuristic method that works by assuming two things:

1.Different trees will result from two different sorts of constituents.

2.With a key prop, the developer may indicate which aspects will be consistent between renderings. (This is why React usually cautions us about including keys in our props.)


React performance optimization

React works very smartly and it optimizes the number of costly DOM operations which is required to the UI. But there are some techniques that help us to boost the react speed a little bit more.

1.Using immutable Data structure. 
2.Function/ Stateless components and React.PureComponent. 
3.Multiple Chunk Files .
4.Dependency optimization.
5.Use React.Fragment to avoid additional HTML element wrappers.
6. Avoid inLine function definition. 
7.Throttling and Debouncing Event Action in JavaScript
8.Avoid using Index as key for map.
9.Avoiding Props in initial States.
10.Use Reselect in Redux to Avoid Frequent Re-render

Prop drilling 
Prop drilling is a process that we need to pass data from the parent component to its child components. 
Suppose you have some Products data in the allProduct component and you want to pass it to the Product component. So, first you need to fetch the data from the api and keep it in a state using the useState hook. Then import the component you want to pass the data just like the code below.

```
import React, { useEffect, useState } from "react";
import { Container, Grid } from "@mui/material";
import Product from "../Product/Products";
 
const ProductPage = () => {
  const [products, setProducts] = useState([]);
  useEffect(() => {
    fetch("https://shielded-anchorage-63737.herokuapp.com/products")
      .then((res) => res.json())
      .then((data) => setProducts(data));
  }, []);
  return (
    <div>
	//prop drilling
          {products.map((product) => (
            <Product key={product._id} product={product}></Product>
          ))}
    </div>
  );
};
 
export default ProductPage;

```