useContext hook

Most of the blogs provide code that has parent and child component placed in the same file. The context is available to both the component. For the components which are placed in different files, we have to extract Context in a separate file.

app.js

import * as React from 'react';
import './style.css';
import Parent from './Parent';
import { TestContext } from './Context';
export default function App() {
  return (
    <div>
      <TestContext.Provider value="Context">
        <Parent />
      </TestContext.Provider>
    </div>
  );
}

Context.js

import * as React from 'react';
export const TestContext = React.createContext();

Child.js

import * as React from 'react';
import { useContext } from 'react';
import { TestContext } from './Context';
const Child = () => {
  const user = useContext(TestContext);
  return (
    <>
      <div>Child </div>
      <strong>{user}</strong>
    </>
  );
};
export default Child;

The context can now be shared easily across the descendent component easily.

Rarely used/ known secrets of Javascript numbers and strings

let num = 1;
console.log(1e1); // 10
console.log(2e1); //20
console.log(2e-1); //0.2
console.log(2e-2); //0.02
console.log(2e-3); //0.002

console.log((123456).toString()); //123456
console.log((123456).toString()); //123456

let num2 = 255;
console.log(num2.toString(16)); //ff
console.log(9999999999999999); //10000000000000000
console.log(0.2 + 0.1 === 0.3); //false
console.log(10_000_000); //10000000

let text = 'Pravin:\n * Abhay\n * Dev\n * Sham';
console.log(text);
/* Pravin:
 * Abhay
 * Dev
 * Sham */

let text2 = 'Pravin\nVarma';
let text3 = `Pravin
Varma`;
console.log(text3 === text2); // true

let text4 = 'Pravin:\tAbhay\tDev\tSham';
console.log(text4); //Pravin: Abhay Dev Sham

let myName = 'Pravin';
console.log(myName.codePointAt(0)); // Character code of P
console.log(myName.codePointAt(0).toString(16)); //Hex code

let charCode = myName.codePointAt(0);
let hexOfNum = charCode.toString(16);
console.log(String.fromCodePoint(charCode)); // get char from code

let str = '';

for (let i = 65; i <= 122; i++) {
  str += `${i}: ${String.fromCodePoint(i)} \t | `;
}
console.log(str);

/*
65: A | 66: B | 67: C | 68: D | 69: E | 70: F | 71: G | 72: H | 73: I | 74: J | 75: K | 76: L | 77: M | 78: N | 79: O | 80: P | 81: Q | 82: R | 83: S | 84: T | 85: U | 86: V | 87: W | 88: X | 89: Y | 90: Z | 91: [ | 92: \ | 93: ] | 94: ^ | 95: _ | 96: ` | 97: a | 98: b | 99: c | 100: d | 101: e | 102: f | 103: g | 104: h | 105: i | 106: j | 107: k | 108: l | 109: m | 110: n | 111: o | 112: p | 113: q | 114: r | 115: s | 116: t | 117: u | 118: v | 119: w | 120: x | 121: y | 122: z |
*/

Using Karma plugin in IntelliJ IDEA to run individual test files

If you are using IntelliJ IDEA and working on test cases and if you want to run test cases in a particular file or a selected test case then you need to follow the following steps.

Go to Preferences -> Go to Plugin section -> Search for Karma -> Hit Apply and then OK. It will start indexing and Run test icon will appear with the line number.

React useMemo example with explanation

import React,{useMemo,useState} from "react";
import "./style.css";

export default function App() {
const [state, setState] = useState(0);
for(let i=1;i<10;i++){
let a=1;
let b = 1;
console.log(useMemo(()=> {console.log('invoked');return a+b},[a,b]))
}
const callMe=()=>{
setState(prevState=>prevState+1)
}
return (
<div>
<h1>Hello StackBlitz!</h1>
<p onClick={callMe}>Start editing to see some magic happen :)</p>
</div>
);
}

React component renders every time it’s state changes. In the above example without useMemo the message will be printed(along with value 2) when we click on the message(I know it’s wrong to have onclick on paragraph) nine times.

If we put useMemo in place then the message wont be printed. Instead, memoized value will be presented on the screen(which is 2; nine times!)

Prevent child from re-rendering in React using React.memo

This is the parent component

import React,{useEffect, useState} from 'react';
import './style.css';
import Child1 from './child1';

export default function App() {
    const [change, setChange] = useState(0);
    const onChange = (e)=>{
        setChange(e.target.value)
    }
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <Child1 change={change}/>
            <input type="text" onChange={onChange} value={change} />
            <p>Start editing to see some magic happen :)</p>
            {change}
        </div>
    );
}

The child component

import React, { useEffect, useState } from 'react';
const  Child1 = React.memo((props)=> {
    useEffect(() => {
        console.log('child Update');
    }, [props.change]);
    return (
        <div>
            <h1>Child1</h1>
            {props.change}
        </div>
    );
},(PrevProps, NextProps)=>{PrevProps.change === NextProps.change})
export default Child1

Using React.memo, you can pass first argument as component and second argument as a function which can have two argument PrevProps and NextProps which you can use to compare the change. If the comparison returns true, then the child won’t re-render.

When you overwrite the previous value by copy pasting, it does not re-renders the component i.e. it does not trigger useEffect!

https://react-childupdate.stackblitz.io/

 

 

A tricky useEffect dependency

The following code returns 1. It is tricky but should be eye opener.

export default function App() {
    const [state, setState] = useState('');
    useEffect(()=>{
        console.log(1)
    },[setState])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}
which is same as
export default function App() {
    const [state, setState] = useState('');
    useEffect(()=>{
        console.log(1)
    },[])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}
The following will throw an error
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
export default function App() {
    const [state, setState] = useState('');
    setState(1);
    useEffect(()=>{
        console.log(1)
    },[])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <p>Start editing to see some magic happen :)</p>
        </div>
    );
}

We need to set state inside event handler function.

export default function App() {
    const [state, setState] = useState(0);
    const onClickHandler=()=>{
        setState(1);
    }
    useEffect(()=>{
        console.log(state)
    },[state])
    return (
        <div>
            <h1>Hello StackBlitz!</h1>
            <button onClick={onClickHandler}>click</button>
        </div>
    );