Skip to main content

Command Palette

Search for a command to run...

React :-

Updated
•7 min read•View as Markdown

React is a powerfull Javascript library used to building fast and interactive user interfaces using reusable components.

Key Features of React :-

  1. Component Based Architecture :- React application are built using components Example :- NavBar, Card,Button

  2. Virtual Dom :- React uses virtual dom to improve performance. instead of updating the whole page react update only changed part

  3. Reuseable component :- we can reuse the component across application

Difference between virtual dom and real dom:-

The Real dom is the actual structure of the webpage that the browser renders.when user do some change then the browser update the entire DOM tree. This process is slow and expensive.

The Virtual dom is lightweight copy of Real dom maintained by the React. When user something changes react updates the virtual dom first and compare it with the previous version and update only the changed part of dom.

What is Component & props :-

Component in React is reuseble piece of UI. and each coomponent is independent and reusable.

Example :-

const Welcome = () => {
  return (
    <div>
       <p>Welcome to the React Js</p>
    </div>
  )
}

export default Welcome

  

Props :-

props means properties are used to pass data from parent component to child component.props are inputs to a component that make it dynamic and reusable.props are readonly . we cannot modify it inside the child.

function App() {
  return <Greeting name="Udit" />;
}

function Greeting(props) {
  return <h1>Hello {props.name}</h1>;
}

State in React Js :-

State is used to store the dynamic data in a component that change over time.When state changes it re renders the component automatically. State is mutable via setter function (like setCount). any changes in state will re render the component

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>{count}</p>
      <button onClick={() => setCount(count1)}>Increment</button>
    </div>
  );
}

When so when button is clicked the count value updates and UI updates automatically.

JSX (Javascript Xml) :-

JSX means javascript xml. It allows the user to write the code similar to html in their javascript files. This jsx will be transpiled into javascript that interact with the browser when the application is built.

Babel :-

Babel is a Javascript compiler which is used to convert the modern javascript code into the version that is understandable by all the modern browser.

Hooks :-

Hooks are the functions that let you use the react features inside the functional component.

Different Types of Hooks :-

  1. useState :- It is used to manage the state data inside the component
import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}
  1. UseEffect :- The useEffect Hook in React allows you to perform side effects in functional components. Side effects are operations that interact with systems outside of React's control, such as fetching data
    Example 1 :-

    import React, { useEffect } from "react";
    
    function App() {
      useEffect(() => {
        console.log("Component mounted");
      //  empty array as a dependency means it runs only on first render.
      }, []);
    
      return <h1>Hello User 👋</h1>;
    }
    
    export default App;
    

Example 2 :-

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

function App() {
  const [count, setCount] = useState(0);

  useEffect(() => {
    console.log("Count changed:", count);
  }, [count]);

  return (
    <>
      <h1>{count}</h1>
      <button onClick={() => setCount(count + 1)}>
        Increment
      </button>
    </>
  );
}

export default App;

When page Loads it logs 0 and when button click it will print updated count.

Dependency When it runs
[ ] only once (after first render)
[state] first render + when state changes
no array every render

3.UseRef :- useRef is used to store a value that does NOT cause re-render and can also access DOM elements directly. useRef will be used when we want to access direct html element.

import React, { useRef } from "react";

function App() {
  const inputRef = useRef(null);

  function handleFocus() {
    inputRef.current.focus();
  }

  return (
    <>
      <input ref={inputRef} type="text" placeholder="Type here..." />
      <button onClick={handleFocus}>Focus Input</button>
    </>
  );
}

export default App;

useRef(null) → It creates reference

ref={inputRef} → It connects input to ref

inputRef.current → actual DOM element .focus() → focuses input

4.useContext :- useContext is a React hook that allows components to access shared data directly without passing props through every level, helping avoid prop drilling.

Step 1 :- Create a context

import { createContext } from "react";

export const ThemeContext = createContext();

Step 2:- Provide Context

import React, { useState } from "react";
import { ThemeContext } from "./ThemeContext";
import Child from "./Child";

function App() {
  const [theme, setTheme] = useState("light");

  function toggleTheme() {
    setTheme(theme === "light" ? "dark" : "light");
  }

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      <div
        style={{
          background: theme === "light" ? "#fff" : "#333",
          color: theme === "light" ? "#000" : "#fff",
          height: "100vh",
          padding: "20px",
        }}
      >
        <h1>Theme: {theme}</h1>
        <Child />
      </div>
    </ThemeContext.Provider>
  );
}

export default App;

Step 3 :- Consume context

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

function Child() {
  const { theme, toggleTheme } = useContext(ThemeContext);

  return (
    <>
      <h2>Current Theme: {theme}</h2>
      <button onClick={toggleTheme}>Toggle Theme</button>
    </>
  );
}

5.useReducer :- It is a React hook used for managing complex state logic by dispatching actions to a reducer function, which determines how the state should change.

we can think :-

useState = simple variable

useReducer = mini state manager

import React, { useReducer } from "react";

// reducer function
function reducer(state, action) {
  if (action.type === "increment") {
    return { count: state.count + 1 };
  }

  if (action.type === "decrement") {
    return { count: state.count - 1 };
  }

  return state;
}

function App() {
  const [state, dispatch] = useReducer(reducer, { count: 0 });

  return (
    <>
      <h1>{state.count}</h1>

      <button onClick={() => dispatch({ type: "increment" })}>+</button>

      <button onClick={() => dispatch({ type: "decrement" })}>-</button>
    </>
  );
}

export default App;

Controlled Component :-

A controlled component is a form element whose value is controlled by React State

import { useState } from "react";

function ControlledInput() {
  const [value, setValue] = useState("");

  return (
    <input
      value={value}
      onChange={(e) => setValue(e.target.value)}
    />
  );
}

UnControlled Component :-

An uncontrolled component stores its own state inside the DOM.

import { useRef } from "react";

function UncontrolledInput() {
  const inputRef = useRef();

  function handleSubmit() {
    console.log(inputRef.current.value);
  }

  return (
    <>
      <input ref={inputRef} />
      <button onClick={handleSubmit}>Submit</button>
    </>
  );
}

prop drilling

Prop Drilling is a situation where you pass data from parent component to deeply nested child component through multiple intermediate components

function App() {
  return <Parent name="Udit" />;
}

function Parent(props) {
  return <Child name={props.name} />;
}

function Child(props) {
  return <GrandChild name={props.name} />;
}

function GrandChild(props) {
  return <h1>{props.name}</h1>;
}

we can avoid the Prop drilling using context api to share the data globally

Example :-

Step 1: Create Context

import { createContext } from "react";

export const UserContext = createContext();

Step 2: Provide Data [Now data is globally available]

import { UserContext } from "./UserContext";

function App() {
  return (
    <UserContext.Provider value="Udit">
      <Parent />
    </UserContext.Provider>
  );
}

Step 3 :- Access the props from context api

import { useContext } from "react";
import { UserContext } from "./UserContext";

function GrandChild() {
  const name = useContext(UserContext);

  return <h1>{name}</h1>;
}

State Uplifiting :-

State lifting means moving state from child components to a common parent so multiple components can share and update it.

Example :-

function Input() {
  const [text, setText] = useState("");
  return <input onChange={(e) => setText(e.target.value)} />;
}

function Display() {
  return <h1></h1>;
}

Input has state but Display cannot access it.

Lift State to Parent component :-

import React, { useState } from "react";

function App() {
  const [text, setText] = useState("");

  return (
    <>
      <Input text={text} setText={setText} />
      <Display text={text} />
    </>
  );
}

function Input({ text, setText }) {
  return <input value={text} onChange={(e) => setText(e.target.value)} />;
}

function Display({ text }) {
  return <h1>{text}</h1>;
}

export default App;