Showing posts with label React. Show all posts
Showing posts with label React. Show all posts

Thursday, 19 December 2024

React useLayoutEffect Hook

useLayoutEffect Work synchronously. and useEffect work with asynchronously.

useEffect it fires synchronously after all DOM loading is done loading.

useLayoutEffect call before DOM update.

App.js file : use hook : useEffect and useLayoutEffect both, but in console you can check first render useLayoutHook. so you can some time calculation or other stuffs before render DOM, you can go with useLayoutEffect hook.

import { createContext, useState, useLayoutEffect, useEffect } from 'react';
import './App.css';

function App() {
  let [name, setName] = useState('Ankit Vyas');

  useEffect(() => {
    console.log('call useEffect.');
    setName('Vyas');
  }, []);

  useLayoutEffect(() => {
    console.log('call useLayoutEffect.');    
    setName('Ankit');
  }, []);

  return (
    <div className="App">  
      My name is : {name}
    </div>
  );
}

export default App;

React portals

React-portals

React write something outside of root element, so we can use React portals.

public/index.html : after root div add one more div with id name is : 'root-test-portal'

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />   
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <div id="root-test-portal"></div> // added this div with id here.
  </body>
</html>

App.js file code

import './App.css';
import TestPage from './Pages/TestPage';
import TestReactPortals from './Pages/TestReactPortals';

function App() {
  return (
    <div className="App">
      <TestPage />
      <TestReactPortals />
    </div>
  );
}

export default App;

/pages/TestReactPortals.js file code

import React, { Component } from "react";
import ReactDom from 'react-dom';

class TestReactPortals extends Component  {
    render() {
        return ReactDom.createPortal(
            <h5>Test React Portals...</h5>,
            document.getElementById('root-test-portal')
        );
    };
}

export default TestReactPortals;

Pages/TestPage.js file code

import React from "react";

const TestPage = () => {
    return (
        <>
            <h2>Test page</h2>
        </>
    );
}
export default TestPage;

Tuesday, 17 December 2024

React Custom Hook

 


Custom hooks must start with keyword is 'use'. Like : useFetchData().

Custom hooks are functions that use one or more times.

Custom hooks create with used also react hook if needed.

app.js file code

import { createContext, useState } from 'react';
import useFetch from './customhooks/useFetch';

function App() {
  const dataFetch = useFetch('Pass API path');

  return (
    <div className="App">
      {dataFetch.map((res) => {
        return (<h4 key={res.id}>
          res.title
        </h4>
        )
      })}
    </div>
  );
}

export default App;

customhooks/useFetch.js

import { useEffect, useState } from "react";

const useFetch = (url) => {

    const [responses, setResponses] = useState([]);

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

    return responses;
}
export default useFetch;

React useEffect Hooks

React : useEffect Hooks : initialise, mounting, updating, unmounting.

React app run and check console also for count.

import { useEffect, useState } from "react";

function App() {

  //useEffect Hooks  : initialise, mounting, updating, unmounting
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Component mounted or updated. Current count:", count);
   
    return () => {
      console.log("Cleanup before component unmounts or before next effect");
    };
  }, [count]);

 
  const increment = () => {
    setCount(count + 1);
  };
 
  const decrement = () => {
    setCount(count - 1);
  };

  return (
    <div>
      <h1>Counter: {count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );

}

export default App;

Monday, 16 December 2024

React useContext Hook

Pass data parent to child component and child to parent.

Provide using pass value. parent to child component.

Without manually pass data.

Run this code and see the output. using Provider in app.js file pass day Tuesday. and in child component ChildUseContext button onClick pass Day data to parent component.

App.js file code

import { createContext, useState } from 'react';
import ChildUseContext from './Pages/ChildUseContext';

export const globalDay = createContext();

function App() {
  let [day, stDay] = useState('Tuesday');

  let setDay = (day) => {
    console.log('day------>', day);    
    stDay(day);
  }

  return (
    <div className="App">
      <globalDay.Provider value={{day:day, setDay}}>
        <ChildUseContext />
      </globalDay.Provider>
    </div>
  );
}

export default App;

Pages/ChildUseContext.js file code

import React, { useContext } from "react";
import { globalDay } from "../App";

function ChildUseContext() {    
    const {day, setDay} = useContext(globalDay);
   
    return(        
        <>
            <h3>ChildUseContext Example : Day {day}</h3>            
            <button onClick={() => { setDay('Monday'); }}>Click Day</button>            
        </>
    );
}
export default ChildUseContext;

React useMemo Hook

This hook use with functional component.

Also called Higher order component.

Improve App Performance.

Store Memoized Value.

Run this below code and see the difference in console. if we click on count button then show incrementData count in console.

App.js file code

import { createContext, useState } from 'react';
import MemoHook from './Pages/MemoHook';

function App() {
 
  return (
    <div className="App">
      <MemoHook />
    </div>
  );
}
export default App;

Pages/MemoHook.js file code

import React, { useMemo, useState } from "react";

function MemoHook() {
    let [count, setCount] = useState(2);
    let [item, setItem] = useState(22);
   
    console.log("MemoHook count: ", count);
    console.log("MemoHook item: ", item);  

    let incrementData = useMemo(() => {
        console.log('incrementData--->', count, item);        
    }, [count]);
   
    return(        
        <>
            <h3>MemoHook Example : Count {count} : Item {item}</h3>
            {incrementData}
            <button onClick={() => { setCount(count+1); }}>Click Count</button>
            <button onClick={() => { setItem(item+1); }}>Click Item</button>
        </>
    );
}
export default React.memo(MemoHook);

React Pure Components

Restrict the re-rendering when the state and props are value same.

Extend a class with Pure Component.

Run this below code and see the difference in console.

App.js file code

import { createContext, useState } from 'react';
import './App.css';
import PureComponentExample from './Pages/PureComponent';
import NormalComponentExample from './Pages/NormalComponent';

function App() {
  return (
    <div className="App">
        <NormalComponentExample />
        <PureComponentExample />
    </div>
  );
}

export default App;

Pages/PureComponent.js file code

import React, { PureComponent } from 'react';
class PureComponentExample extends PureComponent {
    constructor() {
        super();
        this.state = {
            count: 5
        }
    }

    render() {
        console.log("PureComponent : ", this.state);
        return (
            <>
                <h3>PureComponent Example : {this.state.count}</h3>
                <button onClick={() => { this.setState({ count: 10 }) }}>Click</button>
            </>
        );
    }
}
export default PureComponentExample;

Pages/NormalComponent.js file code

import React, { Component } from 'react';
class NormalComponentExample extends Component {
    constructor() {
        super();
        this.state = {
            count: 5
        }
    }

    render() {
        console.log("NormalComponent : ", this.state);
        return (
            <>
                <h3>NormalComponent Example : {this.state.count}</h3>
                <button onClick={() => { this.setState({ count: 10 }) }}>Click</button>
            </>
        );
    }
}
export default NormalComponentExample;