React
npx create-react-app@5 project-name #Using create-react version 5
npx create-react-app@5 project-name #Using create-react version 5

Component

import React from "react";
import ReactDOM from "react-dom/client";

function App() {
  return <h1>Hello React!</h1>;
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);
import React from "react";
import ReactDOM from "react-dom/client";

function App() {
  return <h1>Hello React!</h1>;
}

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

JSX

Props

One-Way Data Flow

Never from Down to Top of the component tree

React Fragments

Make it possible to group elements without adding extra wrapping tag like <div></div>

//Baisc React fragment
<>
</> 
//Or when need a key for the element
<React.Fragment key={}>
</React.Fragment>
//Baisc React fragment
<>
</> 
//Or when need a key for the element
<React.Fragment key={}>
</React.Fragment>

Children prop

// In parent component:
function parent(){
return(
<ChildComponent> children</ChildComponent>
)
}

//In the child component 
funcion ChildComponent(props){
const childrenData = props.children
}
// In parent component:
function parent(){
return(
<ChildComponent> children</ChildComponent>
)
}

//In the child component 
funcion ChildComponent(props){
const childrenData = props.children
}

React State & Event

Event Handling

onClick={}
onMouseEnter={}
onClick={}
onMouseEnter={}

State

const [state,setStateFunction] = useState()
const [state,setStateFunction] = useState()

Updating State based on Current State

onClick={()=>setState(prevState=>!prevState)} //Alter the state
onClick={()=>setState(prevState=>!prevState)} //Alter the state

Controlled Element

When to use State

433f89132379c1dfe047bd89b8b288bf.png

Deriving State

Component Categories

Component Composition

9ec86c33a91612fa1236fdb31873c24e.png

How React works

COMPONENT VS. INSTANCE VS. ELEMENT

8a3b224140fa626413db575b6bd2b476.png
b5c9d425bd72cf4aa3a717ba04958592.png

HOW COMPONENTS ARE DISPLAYED ON THE SCREEN

HOW RENDERS ARE TRIGGERED

The Render Phase

Virtual DOM:

The RECONCILER of React - Fiber

HOW DIFFING WORKS

The Key prop

Usage 1: Using keys in lists

ec18c88e3b55e7816a6aea0790771ecb.png

Usage 2: Using keys to reset State of content at fixed position

THE COMMIT PHASE AND BROWSER PAINT

The overview of the React handeling process

2f7acbd07bd0aee26671a90da06ad4c9.png

THE TWO TYPES OF LOGIC IN REACT COMPONENTS

  1. RENDER LOGIC
    • Code that lives at the top level of the component function
    • Participates in describing how the component view looks like
    • Executed every time the component renders
  2. EVENT HANDLER FUNCTIONS
    • Executed as a consequence of the event that the handler is listening for (change event in this example)
    • Code that actually does things: update state, perform an HTTP request, read an input field, navigate to another page, etc.

Side Effect vs Pure Function

RULES FOR RENDER LOGIC

State update and batched

Events in React

HOW REACT HANDLES EVENTS

51ddbc4c46308a06d5b90e39d8a25e53.png

SYNTHETIC EVENTS

5e7cad28a17b0a98669e681c85e40957.png

Libaries vs Frameworks

be29dfacaad4e393bd4f85b3d7b4a1f1.png
f291c93a27e7fb2d1f8bd3f3a43cd786.png
23db1ddd4e6b43624fb8e5657f9f73f2.png
22e8035646321e4599e88b4726a140a7.png

Debugging

Fragments, Portals & refs

Effect

Component (instance) Lifecycle

446f5e2478ad02410f772693dee7f68e.png

Side effects in React

Event Handlers useEffect
Executed when the corresponding event happens Executed after the component mounts (initial), and after subsequent re-renders
Used to react to an event Used to keep a component synchronized with some external system (e.g., with data from an API)

useEffect() Hook

The UseEffect Dependency Array

useEffect(()=>{
    console.log("This runs every time after the state updated(e.g. user input or component being rendered)")
})

useEffect(()=>{
    console.log("This runs only at the first time the component rendered, e.g. refresh the webpage")
},[])

useEffect(()=>{
    console.log("This runs every time when anyone of the dependencies reevaluated")
},[denpendency1,dependency2,dependency3...])
useEffect(()=>{
    console.log("This runs every time after the state updated(e.g. user input or component being rendered)")
})

useEffect(()=>{
    console.log("This runs only at the first time the component rendered, e.g. refresh the webpage")
},[])

useEffect(()=>{
    console.log("This runs every time when anyone of the dependencies reevaluated")
},[denpendency1,dependency2,dependency3...])

SYNCHRONIZATION & LIFECYCLE of useEffect

useEffect Cleanup

 useEffect(() => {
    const identifier = setTimeout(() => {
      console.log("Checking form validity");
      setFormIsValid(
        enteredEmail.includes("@") && enteredPassword.trim().length > 6
      );
    }, 500);
    return () => {
      console.log("CleanUp!");
      clearTimeout(identifier); //Clear the timer every time before the identifier function runs
    };
  }, [enteredEmail, enteredPassword]);
 useEffect(() => {
    const identifier = setTimeout(() => {
      console.log("Checking form validity");
      setFormIsValid(
        enteredEmail.includes("@") && enteredPassword.trim().length > 6
      );
    }, 500);
    return () => {
      console.log("CleanUp!");
      clearTimeout(identifier); //Clear the timer every time before the identifier function runs
    };
  }, [enteredEmail, enteredPassword]);

Doesn't run for the very first time of the side effect function execution, but runs before every next time the callback function execution

useEffect(()=>{
    console.log('Effect Running');
    
    return()=>{
  console.log('Effect CleanUp');// This cleanup function runs only when the component being removed, as there are no dependencies
    }
    
},[])//No dependencies
useEffect(()=>{
    console.log('Effect Running');
    
    return()=>{
  console.log('Effect CleanUp');// This cleanup function runs only when the component being removed, as there are no dependencies
    }
    
},[])//No dependencies
useEffect(
  function () {
    const controller = new AbortController();
    async function fetchSomeData() {
      try {
        const res = await fetch(URL, { signal: controller.signal });
      } catch (error) {
        console.error(error.message);
      }
    }
    fetchSomeData();
    return function () {
      controller.abort(); //Cleaning up function of Aborting redundant fetch
    };
  },
  [dependency]
);
useEffect(
  function () {
    const controller = new AbortController();
    async function fetchSomeData() {
      try {
        const res = await fetch(URL, { signal: controller.signal });
      } catch (error) {
        console.error(error.message);
      }
    }
    fetchSomeData();
    return function () {
      controller.abort(); //Cleaning up function of Aborting redundant fetch
    };
  },
  [dependency]
);

REACT HOOKS AND THEIR RULES

REFS & useRef

ee35ca1bed7884400e1cb826056c3257.png

Ref vs State

ea5ee9e50318f6e0ccb2535adaeb6930.png

Use Reducer

Styling component

Styling Options in React

26ef72206e91356f181cc0569aec9a99.png

CSS modules

Always use class name for CSS
- or the selector will select all the elements from the entire project
.ClassName :global to select all elements with the classname in the entire project

import styles from the CSS file

React Router

Single Page Applications (SPA)

Router

npm install react-router-dom

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

</BrowserRouter>
    </Routes>
        <Route path="*" element={<Page/>} />
    </Routes>
</BrowserRouter>
import {BrowserRouter, Routes, Route} from "react-router-dom";

</BrowserRouter>
    </Routes>
        <Route path="*" element={<Page/>} />
    </Routes>
</BrowserRouter>

Index Route

Default
<Route index element={<Homepage />} />

<Link to='/pricing'></Link>
<NavLink to='/pricing'></Link> NavLink makes it active when it's on the page

Outlet

similar to {children}

Context API

  1. Provider: gives all child components access to value
  2. Value: data that we want to make available (usually state and functions)
  3. Consumers: all components that read the provided context value
    3980b621b44f14f64116c0855a5da1e2.png

Usage

import {useContext, createContext} from "react";

const PostContext = createContext(); //1. Create a new context
function PostProvider({ children }) {
return (
    //2. Provide Value to Child Components
    <PostContext.Provider
      value={{
        posts: searchedPosts,
        onAddPost: handleAddPost,
        onClearPosts: handleClearPosts,
        searchQuery,
        setSearchQuery,
      }}
    >
      {children}
    </PostContext.Provider>
  );
}

//3. Consume the context
const {onAddPost} = useContext(PostContext);
import {useContext, createContext} from "react";

const PostContext = createContext(); //1. Create a new context
function PostProvider({ children }) {
return (
    //2. Provide Value to Child Components
    <PostContext.Provider
      value={{
        posts: searchedPosts,
        onAddPost: handleAddPost,
        onClearPosts: handleClearPosts,
        searchQuery,
        setSearchQuery,
      }}
    >
      {children}
    </PostContext.Provider>
  );
}

//3. Consume the context
const {onAddPost} = useContext(PostContext);

Performance Optimization(Memo,useCallback)

Memo