Skip to content

Welcome to the React.js Notes repository! πŸš€ Dive into the world of React.js development and take your skills to the next level with comprehensive notes, tips, and tricks.πŸ’š

Notifications You must be signed in to change notification settings

parthmern/React-JS

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

36 Commits
Β 
Β 

Repository files navigation

React-JS

❀️ What is React ?

βž” Js library used to create UI
βž” library = A programming library is a collection of prewritten code that programmers can use to optimize tasks ( in C lang we use the pow(a,b) pre-defined function with using stdlib.h library

βž” React is all about components so it is component based architecture

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ Why we need React ?

βž” JS is based on imparative approach
βž” React is based on declarative approach

βž” imparative approach means line by line
βž” declarative approach means we
βž” SPA ( single page application ) approach (like netflix )
βž” Development is faster than vanilla JS

βž” React alternatives = angularJs , vueJs

  1. reusablity (using components)
  2. DRY (do not repeate yourself)
  3. readability
  4. SOC(seperation of concern)
  5. maintainability

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’œ Comopnent

βž” a piece of code that used multiple times - reusable piece of code
βž” ( like custom html element that we can use multiple times )
βž” same work as Function ( create js file and write function )

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’› Installation

βž” Install node js ( link and check node -v and npm -v )
βž” Vs code

βž” React installation ( vidLink )
βž” if above is not working then try this

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ Direct starter pack

startert pack

βž” package.json = dependencies/version/scripts are avialabe here
βž” src folder
src > index.js = first file that excecutes when page load / entry point of js = here react creates 'root' that fetch from index.html
src > index.css
= file that contains css for index.js file src > app.js or app.jsx
βž” public folder
public > index.html = contains 'root'
βž” nodeModules folder

⚠️ firstly excecutes index.js file then it goes to index.html file to get the <root> div and it converts rootDiv to react-root and then it render <App> from App.js or App.jsx and here App.js contains html code

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’š Create Component

βœ”οΈ βž” first create components folder in src
βœ”οΈ βž” then src > components then create Item.js and Item.css
βœ”οΈ βž” Item.js looks like

import './Item.css' ;      //here first import .css file

function Item()            //then create function that returns Html code
{
  return(

    // html codes
    <p className="parth"> hello </p>

  );
}

export default Item ;      //then export the function that we can use in App.js

here in Item.js we are actually writing JSX (JavaScrpit XML means JS with Html code) code so we cannot define html element class directly because js already have predefined class component so here in jsx we have to use className='xxxxx' except class='xxxxx'

━━━━━━━━━━

βœ”οΈ βž” Item.css looks like

.parth
{
  text-align: center;
  background-color: aqua;
}

// same as actual css

━━━━━━━━━━

βœ”οΈ βž” use of component in App.js file

import Item from './components/Item' ;        // here we are importing Item from `Item.js`
                                              //  components > Item(exported)

function App()
{
  return(

    // html codes
    // using Item componenet
    <Item> </Item>

  );                            
}

export default App;                           // exporting `App.js` because we have to use this in `index.js` the first entry point

━━━━━━━━━━

βœ”οΈ βž” EXTRA index.js looks like this

import React from "react";
import ReactDOM from "react-dom/client";
import App from "./App";
import "./index.css";

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

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ PROPS - properties

πŸ’€ Extra - In JSX how to use varibales value

function any()
{
    const var = 5 ;

    return (
    <p> {var} </p>
    );

}

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

βœ”οΈ βž” here we have to send properties from App.js file like this

function App()
{
  const itemTwoName = "patel" ;                                       //⚠️ here we are doing PARENT to CHILD communcation using props matlab parent kuch value send kar rha hai child ko

  return (
    <div>
         //one way
         <item name = "parhu" > </item>

         //second way
         <item name ={ itemTwoName } > </item>

         //children of prop
         <item> i am children which is between and inside the component </item>
    </div>
 );
}

βœ”οΈ βž” in Item.js we have to change things like

function Item(props)                              
{

 const pname = props.name ;

  return(
         <div>                                    // IMP = if there are more than one html line then put them into <div> TAG

             <p> {pname} </p>                          
             { props.children }                   // here we can acces " i am children..."

          </div>
  );
}

//---------------------------------------

function Item( {name,children} )                 // here "name" that we have sended and "children" is bydefault to access children
{


  return(
         <div>                                    

             <p> {pname} </p>                          
             { children }                   // here we can acces " i am children..."

          </div>
  );
}

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’› PROPS as Event handling

function clickHandlerFunction()
{
  //anything that you want to perform
}

// Event Handling
<button onClick={clickHandlerFunction} > xxxx </button>

// another way
<button onClick={() => {
    clickHandlerFunction();
}}>
  xxxx
</button>

⚠️ always remeber that while using callbackFuntion avoid to write this callbackFuntion() beacuse () means that automatically calls the function without any Event done

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

❀️ State (useState Hook

βž” for Re-Rendering purpose
βž” like i want to change innerText / value updation of any element when i click on the button but to do this i have to do Re-Rendering

βž” Before state

function clickedBtn()
{
  const title = "oldValue" ;

  function cbFunc()
  {
    title = "newValue" ;
  }

  return(

  <div>
       <h2> {title} </h2>
       <button onClick={cbFunc} > xxxx </button>
  </div>
  
  );
}

// πŸ“ here first react render the whole DOM so the value of title = "oldValue" and it print "oldValue" in <h2> tag  but when we clicked on
// <button> tag that time the value of title = "newValue" changed so that time again Render is not possible and the again print is not possible so NOT any CHANGES in <h2> tag output



βž” βœ”οΈ After state
import React, {useState} from 'react';               // first import {useState} which is react-Hook(utility function)

function clickedBtn()
{
  const [title,valueUpdateFunc] =useState("oldValue");             //useState returns 2 things as array form first is newValue of variable and function for updating value (using destructing js method)

                                                        // syntax = const [variableName , valueUpdateFunc] = useState("oldValue");
  function cbFunc()
  {
    valueUpdateFunc("newValue");
  }

  return(

  <div>
       <h2> {title} </h2>
       <button onClick={cbFunc} > xxxx </button>
  </div>
  
  );
}

// πŸ“ after clicked on <button> there is also re-Redering and the value of <h2> updated to new value on UI

πŸ“‘ HomeWork =

1 = Why React Hook useState uses const and not let

2 = what is immutable react js - combined with useState que

3 = React setState/useState happens instantly or takes time



🚨 EROORS=
βž” img is a void element tag and must neither have children nor use dangerouslySetInnerHTML. ==> then write <img /> in just single closing



πŸ“‘ Extra for FORM =
βž” get the value of input field that inserted by user using (event) and event.target.value word
βž” how to set value of any text field value = { xyz } it can set value as "xyz" in inputfield


⚠️ State Lifting UP= Communicate from CHILD to PARENT ( matlab child value send krega parent ko )

βž” app.js means PARENT looks like this


function App() {

  function ParentValue(data)
  {
     console.log(data);
  }

  return (

    <div>
      <Child ParentValueFunc={ParentValue}></Child>          //here using props we are sending function to the Child
    </div>
    
  );
}

βž” Child.js means CHILD looks like


function Child(props){

    props.ParentValueFunc("dataaa Inside secreate");             //here ParentValueFunc get the parameter as data = "dataaa Inside secreate" 
    
    return(<p>hell insider here</p>);
}

so we can send the value from CHILD to PARENT using function with parameter like above

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’œ useEffect ( raect hook )

βž” manage side-effects (if i do any action at one component then there is also some changes on another component - ex.changing doc title, modifying state of parent component,api calls,changes in DOM )
βž” every RENDER of UI useEffect will excecute
βž” agar aap kuch kaam karwane chahte ho UI render means UI me changes hone k baad tab aap useEffect use kar sakte ho

import {useEffect, useState} from "react";           // first import

function App()
{

   const [text,setText] = useState('') ;

//------------------------------------------
  // VARIATION-1️⃣ (every render)

  useEffect( () => {
    console.log("UI render Done");} 
  );

//------------------------------------------
  // VARIATION-2️⃣  (first render - when app.js fully renderd for first time)

  useEffect( ()=>{
    console.log("UI rendere done");
  },[] );

//------------------------------------------
  //VARIATION-3️⃣ (first render + whenever dependency changes)                  // firts render + whenever variable "text" changes this useEffect runs

  useEffect(()=>{
    console.log(" text changed observed");
  } , [text] )

//------------------------------------------
  //VARIATION-4️⃣ (to handle unmounting of components)

  useEffect(()=>{
    //add event listener
    console.log("listener added");

    return ()=>{ console.log("listener removed"); }
  })                                                                            //IMP= first run "listener removed" then run "listener added"

 // OR-----------

  useEffect(() => {
    const handleClick = () => {
      console.log('Button clicked!');
    };

    // Add event listener when component mounts
    // generally with hight and width types of or mouse move x,y poisition types of events
    console.log('Listener added');
    document.addEventListener('click', handleClick);

    // Remove event listener when component unmounts
    return () => {
      console.log('Listener removed');
      document.removeEventListener('click', handleClick);
    };
  }, []);


//---------------------------------------------------------------------------------

  function changeHandler(event){
    setText(event.target.value)
    console.log(text);
  }

  return (
    <div className="App">
      <input type="text" onChange={changeHandler} />
    </div>
  );

}


βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ Array methods

βž” using array , if we want to create multiple components at a time then use array.map( callBackFunc )
βž” if we want to do filter then use array.filter (callBackFunc)

items.map( (item)=> { return (<div>{item}</div>) } );

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

❀️ React Forms

βž” form handleing is difficult in js because everytime we have to create different functions to save the value of all fields in form


function App() 
{

  const [formData,setFormData] = useState(
    {
      firstName : "" ,
      lastName : "",
    }
  );

  function changeHandler(event){
    setFormData( (prevFormData)=>{
      return {
        ...prevFormData,
        [event.target.name] : event.target.value 
      }
    } )
  }

  return (
    <div>
      <form>
        
        <input type="text" placeholder="first name" onChange={changeHandler} name="firstName" ></input>
        
        <input type="text" placeholder="last name" onChange={changeHandler} name="lastName"></input>
        
      </form>
    </div>
  );
}


// here every changes on <input> tag , the changeHandler function will run
// and in function setFormData will take return the object with value which is already named as `formData`
// the under process in return => it take previousObject with all changed properties and then access that property using the `name` that given in html element
// means 1) previous state copy 2) element trigger and value update

βž” JS topic= referance link of spread operator with object

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’› Controlled Components

βž” maintain state inside component

 <input type="text" placeholder="first name" onChange={changeHandler} name="firstName" value={formData.firstName}></input>
        
 <input type="text" placeholder="last name" onChange={changeHandler} name="lastName" value={formData.lastName} ></input>

// here we are also re-rendering values from formData object in the components
// matalab jab bhi formData ki state change hogi then tab har ek components jisme value={formData.something} dali hui hai uski value b re-render hogi
// bascially formData me jo bhi value aarhi hai usko hum uske original components me update kar rhe hai

βž” some imp of react form handeling with checkBox

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’š React Router

βž” SPA - single page application ( only one html file where changes happens dynamically and if you click anywhere no reloading )
βž” React Router is a popular library for handling routing in React applications.(route-path)
βž” it allows you to create single-page applications with multiple views, each represented by a specific URL.
βž” This makes it possible to navigate between different sections(homepage,about,support section) of your application without triggering a full page reload.

// installation

npm install react-router-dom

βž” then index.js page

import { BrowserRouter } from 'react-router-dom';

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

βž” then creates different Components like Home,Support,NotFound
βž” then in app.js

import { Routes, Route, Link, NavLink} from "react-router-dom";

// and import all pages(components) here

function App(){

return (
<div>

     <div>
          <Link to="/">Home</Link>                              //here "Link" works like <a> tag and "to" works like href="/" attribute
          <NavLink to="/support">support</NavLink>              //here "NavLink" is same as "Link" but it adds .active class in active component so easy to identify active
     </div>

     <Routes>
        <Route path="/" element={<Home/>}></Route>
        <Route path="/support" element={<Support/>}></Route>
        <Route path="*" element={<NotFound/>}></Route>          // * means universal excluding mentioned paths
      </Routes>

</div>
)
}


βž” here "/" is home and "/support" is the child of / (home) > /support --- and because of this we can do NESTED ROUTING

βž” / Β  Β  Β  Β  Β  Β  ---> parent
βž” /support Β  Β  Β  ---> in / there is support --- child
βž” /about Β  Β  Β  ---> in / there is about --- child

// nested-routing

<Routes>

         <Route path="/" element={<Home/>}>
         <Route path="/support" element={<Support/>}></Route>
         <Route path="*" element={<NotFound/>}></Route>
         </Route>

</Routes>

βž” but here parent element wo child route element ko render nhi hone de raha matalab sab urls par sirf homePage he open ho raha hai

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

img_630e4bb35c8bb

βž” <Outlet> parent route element ke andar child route elemnt ko render karne ki permission deta hai

<Routes>
        <Route path="/" element={<Mainheader/>}>
           <Route index element={<Home/>}></Route>                             // index means default route
           <Route path="/support" element={<Support/>}></Route>
           <Route path="/about" element={<About/>}></Route>
           <Route path="*" element={<NotFound/>}></Route>
        </Route>
      </Routes>

βž” in Mainheader component

import { Outlet } from "react-router-dom" ;

function Mainheader ()
{
   return ( <Outlet></Outlet> ) 
}

βž” <Route index> matches only when the URL path exactly matches the parent route's path and is typically used for rendering default content within a section of your app.
βž” <Route path="*"> acts as a catch-all route, rendering its component when no other route has matched the URL path. It's often used to handle undefined routes or show error pages.


βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

βœ”οΈ useNavigate()

βž” navigation through anywhere
βž” here in Labs page component

import { useNavigate } from "react-router-dom" ;

const Labs =()=>{

    const navigate = useNavigate();

    function clickHandler(){
        navigate("/about");                     // here ("url") means navigate to "url"
    }

   function backHandler(){
        navigate(-1);                           // here (-1) means it navigate to the BACK (PREVIOUS) opened page
    }

    return(
        <div>
            <div>
                this is labs page
            </div>
            <button onClick={clickHandler}>move to about page</button>
            <button onClick={backHandler}>Go Back </button>
        </div>
    )

}

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

βž”βœ”οΈ useParams() hook - chatGpt


βž”βœ”οΈEXTRA imp = add infinite scrolling reactJs library

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ Conditional Operators

βœ”οΈ REACT conditional Operators

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’› api fetching axios method

βž” installing

npm install axios

βž” using

import axios from "axios";

async function fetchData(){

        const url = `https://api.giphy.com/v1/gifs/random?api_key=${API_KEY}`;

        const output = await axios.get(url);

        console.log(output);

    }
    
useEffect(()=>{fetchData()} , [])

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

❀️ Custom HOOK

βž” avoid code duplication
βž” DRY coding + yt explained shortest
βž” custom hooks explained
βž” thapa technical yt

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’™ Context API

βž” Prop Drilling
βž” what is Prop Drilling ? and disadvantages
βž” what is Prop Drilling ?


βž” State Lifting UP
βž” what is ? - send data from child to parents using propFunction


βž” we are sending props from one parent to the child1 then child2 then child3 then child4 - and here the child1, child2, child3 do not need the data but if we want to pass the data from parent to the child4 then we have to do it
βž” it reduce redundancy and performance
βž” so the solution to send data from parent to child4 without including the child1,2,3 -- is context api


βž” Rules:
βž” createContext() = creation of context
βž” provider = context provide
βž” consume

βœ”οΈ jis component me context provide kar rhe hai wo component and us component ke sabhi childrens uus value ko use kar sakte hai --means decenteralized value create kar rhe hai

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž” firstly created a folder named "context" and then created a file named "AppContext.js" in that

export const AppContext = createContext();

function AppContextProvider( {children} )                            //🌐 children means `<App />`
{
   const [loading,setLoading] = useState(false);
   const [page,setPage] = useState(1);

   // data filling
   if(page==1){
   setPage(page+1);
   }

   function handlePageChange(page){
        setPage(page);
    }

   const value = {           //βœ”οΈ value is Object
   loading,
   setLoading,
   page,
   setPage,
   handlePageChange
   }

   // πŸ’― AppContext.Provider because we have created AppContext as createContext

   return <AppContext.Provider value={value}>     //βœ”οΈ we are using above value obj
        {children}                                //🌐 children means `<App />`
    </AppContext.Provider>;

}

βž” we want to use AppContextProvider() on App.js and their children βž” so in index.js file we are doing this and here we are sending <App/> component as {children} in the "AppContext.js"

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

βž” useContext Hook -- consuming data

import { AppContext } from "../context/AppContext";


const value = useContext(AppContext);
// or
const { loading } = useContext(AppContext);

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

🀍 useSearchParams() and useLocation() in react-route

βž” useSearchParams()
βž” useLocation()
βž” LoveBabbar-guide

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’š Redux ToolKit

βž” what is and why ?

βœ”οΈ Installation

npm install @reduxjs/toolkit react-redux

βœ”οΈ create Slice = slices canbe single or multiples ( like SLICEs of one pizza and they create a whole pizza that is STORE )

//πŸ“‚ src > redux folder > slices folder > CounterSlice.js

import { createSlice } from "@reduxjs/toolkit";


//πŸ³οΈβ€πŸŒˆ createSlice mei 3 things ayegi 1)name 2)initialState 3)reducers means obj jis k andar sab functions honge

const initialState={
    value : 0,
}

export const CounterSlice = createSlice({
    name: 'counter',
    initialState,
    reducers : {
        increment : (state) => {
            state.value += 1;
        },

        decrement : (state) =>{
            state.value -= 1;
        }
    }
})

// 🌐 in every slice 
export const { increment, decrement } = CounterSlice.actions;   //exporting functions from actions
export default CounterSlice.reducer;                            //exporting reducer

βœ”οΈ create Store = store k andar sab slices ayegi ( store global state/centeralized state hogi jiske andar sab states store hogi in form of slices )

//πŸ“‚ src > redux folder > store.js

import { configureStore } from '@reduxjs/toolkit';

import CounterSlice from './slices/CounterSlice';

const store = configureStore({

  reducer : {
        counter : CounterSlice ,                         // idhar "reducer" obj k andar sabhi slides ayegi ==> name : sliceName
    },                                                   // agar ERRORS aarhe hai like( Store does not have a valid reducer) toh `CartSlice.reducer` try kro

})

export default store;

βœ”οΈ Connect reduxToolkit with reactJs using <Provider>

import { Provider } from "react-redux";
import store from "./redux/store";

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <Provider store={store} >
    <App />
  </Provider>
);

// aab <App/> k andar k sare components use kar payenge redux States ko

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

useSelector() βœ”οΈ Access state/ value from Slice

import { useSelector } from "react-redux";

const value = useSelector( (state)=> state.counter.value )

//πŸ“EXPLAINED----------------------------------------------------------------
// here useSelector( callBack function that returns the value )
// sabse pehele call store me jati hai then wo slice me jati hai

// state => { counter: {value: 0} }
// state.counter => {value: 0}
// state.counter.value => 0

// matlab "state" k andar sabhi slices hongi and us slices k andar unki value hongi
// idhar sirf ek slice hai jiska name "counter" diya tha and uski initialState(initialValue) = 0 define ki thi

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

useDispatch() βœ”οΈ Access functions(reducers)

import { useDispatch} from "react-redux";
import { decrement, increment } from "../redux/slices/CounterSlice";

function CounterComponent()
{
   const dispatch = useDispatch();

   return(
   <div>
      <button onClick = { ()=>dispatch( increment() ) } > Increment </button>
      <button onClick = { ()=>dispatch( decrement() ) } > Decrement </button>
    </div>)

}

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βœ”οΈ Access Input parameters using "action.payload"

.
.
.
reducers : { 
   add : (state,action) => { ( state + action.payload ) }        //state means present value -- and -- action.payload means passed argument
}

//-------------------------------
//passed arguments from anywhere

dispatch(add(5)) ;

🎼redux devTool extension for checking all presentState

β€οΈβ€οΈπŸ’šβ€οΈβ€οΈ IMP READABLE chatgpt - with combinereducer

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

❀️ useReducer hook

βž” if you want to use multiple useState() then to avoid this you can use this
βž” technical-thapa
βž” gpt

🚨 Explained in amazon clone by cleaver programmer



βž” with context-api

//πŸ“‚ src > context > StateProvider.js

import React, { createContext, useContext, useReducer } from "react";

export const StateContext = createContext();

export const StateProvider = ({ reducer, initialState, children }) => (
  <StateContext.Provider value={useReducer(reducer, initialState)}>
    {children}
  </StateContext.Provider>
);

//anywhere we can use useStateValue() instead of using useContextHOOK which is useContext(StateContext)
export const useStateValue = () => useContext(StateContext);

βž” reducer file which have reducer initialState and reducer

//πŸ“‚ src > context > reducer.js

export const initialState = {
  user: null,
  playlists: [],
}

const reducer = (state, action) =>
{
  console.log(action);

  switch (action.type)                  // we can also use IF-ELSEIF-ELSE here insted of switch
  {
    case "SET_USER" :
      return {
        ...state,
        user: action.user,
      };

   case "SET_PLAYLISTS" :
      return {
        ...state,
        playlists: action.playlists,
      };

   default :
      return state;

    }
}

export default reducer;

βž” how to joint context-api

// πŸ“‚ index.js

import reducer, { initialState } from "./reducer";  //πŸ“‚ src > context > reducer.js

ReactDOM.render(
  <React.StrictMode>
    <StateProvider initialState={initialState} reducer={reducer}>
      <App />
    </StateProvider>
  </React.StrictMode>,
  document.getElementById("root")
);

βž” use useReducer() hoook

const [state,dispatch] = useDataLayerValue();
//or
const [state,dispatch] = useContext(stateContext);
//or
const [{user,playlists} ,dispatch] = useDataLayerValue();   //console.log(user); -- everytime updated like useState

//console.log("state ==",state); // initialValues {user: null,playlists: []} OTHERWISE latestValuesOfInitialState {user: "updatedValue",playlists: []}
//console.log("dispatch ==",dispatch); // function to set initialValues

dispatch({
  type : "SET_USER",
  user : "updatedValue",
});

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ’› useRef()

βž” use reference have 2 uses examples
βž” example 2 is like .getElementbyId and .getElementbyClassname after doing ref.current
βž” example 2 of getting DOM element

βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–

πŸ“› Imp errors

βž” maintaining clickHandler or any function inside mapped component that render many times

// ye component map function k andar hoga so many timne run hoga ye same component

function clickHandler(item){
    //
}

return(
   <div
   onClick={()=>{clickHandler(item)}}                  // avoid to do like this "onClick={clickHandler(item)}"
   >
   </div>
)

βž” react toaster means notification popup - link

🧩 CHEAT-SHEET 🎼 πŸŽ‡

🎯 by LoveBabbar
🎯 random
🎯 by tutorialsPoint
🎯 imp topics to learn
βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–βž–
♻️ @ Created by Parth with πŸ’š

About

Welcome to the React.js Notes repository! πŸš€ Dive into the world of React.js development and take your skills to the next level with comprehensive notes, tips, and tricks.πŸ’š

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published