ReactJS

 Introduction :

What is ReactJS?

1. ReactJS is a JavaScript library used to build UI. 

2. Its main focus is on UI. 

3. It follows component based architecture like header, footer, main content, side nav.

4. DOM updates are handle gracefully in react

5. Component based manage their own state then compose them to make complex UIs.

6. use ES6 - ES6, also known as ECMAScript 2015. ES6 is a major update to JavaScript that includes new syntax and features aimed at making the language more powerful and easier to use.


  • Arrow Functions: Concise syntax for writing functions.
  • Classes: Syntax for creating objects and inheritance.
  • Modules: Import and export statements for modular code.
  • history :

    Initial Release to the Public (V0.3.0) was in July 2013.

    Created and Maintained by facebook.

    Facebook Software Engineer, Jordan Walke, created it.

    What we need :

    1. Variables and Scope: Understanding how variables are declared (using var, let, const) and their scope (global vs. function vs. block scope).

    1. Data Types: Familiarity with primitive data types (like string, number, boolean, null, undefined) and complex data types (such as object, array, function).

    2. Functions: Knowing how to define functions, use arrow functions, and understand function scope and closures.

    3. Arrays and Objects: Manipulating arrays (map, filter, reduce) and working with objects (object literals, destructuring, spreading).

    4. ES6+ Features: Being comfortable with modern JavaScript features like arrow functions, template literals, destructuring, spread/rest operators, and let/const for variable declarations.

    5. DOM Manipulation: Basic knowledge of how the Document Object Model (DOM) works and how JavaScript interacts with HTML elements.

    6. Event Handling: Understanding how to handle events in JavaScript and React (onClick, onChange, etc.).

    7. Modules and Imports: Familiarity with ES6 modules (import/export) and how to organize and reuse code effectively.

    1. React Basics: While not strictly JavaScript, having a conceptual understanding of what React is (a JavaScript library for building user interfaces) and its core principles (like components, JSX, state, and props) will be very helpful.

    React Setup :

    Node.js

    You can download it from: https://nodejs.org/en/


    1. using vite 

    npm create vite@latest my-app --template react


    2. using npm

    npm install -g create-react-app appName;

        
         3. using npx 
         npx create-react-app my-app


    Creating our first react app

     Run this command to create a React application named my-react-app:

    npx create-react-app my-react-app

    OR, you can directly make your application without specifying a name, like this:

    npx create-react-app .

    In this case, all files will be kept in the current directory. 

    Note: When choosing folder name, make sure there are no spaces or capital letters because of npm naming restrictions. 

    Once base application is created, if folder specified you just have to enter the folder. You can use this command to enter:

    cd directory-name

    Then just start up the application with this command:

    npm start



    Features of React

    1. JSX (JavaScript Syntax Extension):

    • JSX combines HTML and JavaScript, allowing you to embed JavaScript objects within HTML elements.
    • It enhances code readability and simplifies UI development.

    Example:

    const name = "GeekforGeeks";
    const ele = <h1>Welcome to {name}</h1>;

    2. Virtual DOM (Document Object Model):

    • React uses a virtual DOM, which is an exact copy of the real DOM.
    • When there are modifications in the web application, React updates the virtual DOM first and then computes the differences between the real DOM and the virtual DOM.
    • This approach minimizes unnecessary re-rendering and improves performance.

    3. One-way Data Binding:

    • React follows one-way data binding, where data flows from parent components to child components.
    • Child components cannot directly return data to their parent components, but they can communicate with parents to modify states based on provided inputs.

    4. Performance:

    React’s virtual DOM and component-based architecture contribute to better performance.
    • Separate components allow efficient rendering and faster execution.

    5. Extension:

    • React has a rich ecosystem and supports various extensions.
    • Explore tools like FluxRedux, and React Native for mobile app development and server-side rendering.

    6. Conditional Statements in JSX:

    • JSX allows writing conditional statements directly.
    • Display data in the browser based on provided conditions.

    Example:

    const age = 12;
    if (age >= 10) {
    return <p>Greater than {age}</p>;
    } else {
    return <p>{age}</p>;
    }

    7. Components:

    • React divides web pages into reusable and immutable components.
    • Component-based development simplifies code organization and maintenance.

    How does React work?

    React operates by creating an in-memory virtual DOM rather than directly manipulating the browser’s DOM. It performs necessary manipulations within this virtual representation before applying changes to the actual browser DOM. React is efficient, altering only what requires modification.

    Browser-DOM-Virtual-DOM

    my-react-app/
    ├── public/
    │   ├── index.html
    │   └── ...
    ├── src/
    │   ├── assets/
    │   │   └── images/
    │   ├── components/
    │   │   ├── Header.js
    │   │   ├── Footer.js
    │   │   └── ...
    │   ├── pages/
    │   │   ├── Home.js
    │   │   ├── About.js
    │   │   └── ...
    │   ├── services/
    │   │   └── api.js
    │   ├── styles/
    │   │   ├── main.css
    │   │   └── ...
    │   ├── utils/
    │   │   ├── helpers.js
    │   │   └── ...
    │   ├── App.js
    │   ├── index.js
    │   └── ...
    ├── .gitignore
    ├── package.json
    └── README.md

    File Structure Breakdown

    1. public/:

      • This directory contains the index.html file and other static assets like images, fonts, or manifest files that need to be served as-is by the web server.
      • index.html: This is the main HTML file where your React application is initially rendered. It typically includes a <div> or another HTML element where React will inject the application's UI.
    2. src/:

      • This is where most of your application code resides, organized into several subdirectories:

      • assets/:

        • Contains static assets such as images, fonts, SVG icons, or any other media files used in your application.
        • Example: assets/logo.png, assets/background.jpg.
      • components/:

        • Contains reusable UI components that are used across different pages or sections of your application.
        • Example: Header.js, Button.js, Modal.js.
        • These components are often designed to be modular and self-contained, promoting reusability and maintainability.
      • pages/:

        • Each route or major section of your application has its own folder or file within this directory.
        • Example: Home.js, About.js, Contact.js.
        • Pages typically represent different views or routes of your application and may use components from the components/ directory.
      • services/:

        • This directory contains services responsible for tasks like API integration, authentication, or other backend interactions.
        • Example: api.js, authService.js.
        • Services encapsulate logic related to data fetching, state management, or any other business logic that interacts with external systems.
      • styles/:

        • Contains CSS files or preprocessor files (like Sass or Less) for styling your components.
        • Example: main.css, variables.scss.
        • Stylesheets define the visual appearance and layout of your application components.
      • utils/:

        • Houses utility functions or helper modules used across your application.
        • Example: helpers.js, constants.js.
        • Utilities provide reusable functions or constants that assist in various tasks throughout your application.
      • App.js:

        • This is the root component of your React application where routing and the main structure of your application are typically defined.
        • It may include routes defined using React Router (<BrowserRouter>, <Switch>, <Route>), global layout components, or state management setup.
        • Example: Defining routes like <Route path="/about" component={About} />.
      • index.js:

        • The entry point of your React application where the app is rendered into the DOM using ReactDOM.render().
        • This file usually imports App.js and injects it into the HTML element specified in index.html.
        • Example: ReactDOM.render(<App />, document.getElementById('root'));.

      • node_modules/: Contains all the npm packages required for your project.

    Flow of the Project

    1. Entry Point (index.js):

      • This file initializes your React application by rendering the App component into the DOM.
      • It typically imports ReactDOM from react-dom and uses ReactDOM.render() to mount the root component (App) onto the HTML page specified in public/index.html.
    2. App.js:

      • Acts as the main container for your application's structure and routing logic.
      • Imports and uses components from pages/ and components/ directories to build different views and UI elements.
      • Sets up routing using React Router to navigate between different pages (Route, Switch, BrowserRouter).
    3. Pages (pages/):

      • Each file (Home.js, About.js, etc.) in this directory represents a specific view or route of your application.
      • These components use reusable UI components from components/ and may fetch data from backend APIs via services from services/.
    4. Components (components/):

      • Reusable UI elements such as headers, footers, buttons, forms, etc., are stored here.
      • These components are designed to be modular, making them easy to reuse across different pages or sections of your application.
    5. Services (services/):

      • Contains modules responsible for API integration, authentication, state management, or any other backend-related tasks.
      • These services are imported and used within components or pages to handle data fetching, state updates, or other asynchronous operations.
    6. Styles and Assets:

      • Styles (styles/): CSS or preprocessor files define the visual appearance and layout of your components.
      • Assets (assets/): Static resources such as images, fonts, or icons that are imported into components/pages as needed.



    JS Methods Sort(), Filter(), Map(), Reduce() :





    Key Differences:

    • Mutability:

      • sort mutates the original array by rearranging its elements.
      • map, filter, and reduce do not mutate the original array; they return new arrays or values.
      • When we say that a method "mutates the original array," it means that the method directly modifies the array it is called upon, altering its contents or structure. This modification happens in-place, meaning the changes affect the original array itself, rather than creating a new array with the modified contents.

    • Return Value:

      • sort returns a sorted version of the original array.
      • map, filter, and reduce return new arrays or values based on the transformations or conditions applied.
    • Usage:

      • sort is primarily used for sorting elements based on custom criteria.
      • map, filter, and reduce are used for transforming, selecting, or aggregating data within arrays.
    • Functionality:

      • sort requires a compare function to define the sorting order.
      • map and filter use a callback function to transform or filter elements based on conditions.
      • reduce applies a callback function to accumulate values into a single result.

    These methods are fundamental for manipulating arrays in JavaScript, each serving distinct purposes depending on the desired operation.

    1. Map

    • What it does: It takes an array and applies a function to each element to create a new array where each element is transformed based on that function.
    • Example: If you have an array of numbers [1, 2, 3], and you use map with a function that doubles each number, you'll get [2, 4, 6].
  • Syntax:


    let newArray = array.map(function(currentValue, index, array) { // Return element for newArray }, thisArg);

    Example 1:

    let arr = [45, 23, 21]

    let a = arr.map(value, index, array)=> {

    console.log(value, index, array);

    return value + index ;

    })

    console.log(a);


    Example 2:


    let array=[11,22,33,44,55,66];


    let arr2=array.map((value,index,array) =>

    {

        let product= value*index;

        console.log(value,index,array,product);

        return product;

    }

    );

    console.log("original array=",array);

    console.log("mapped array=",arr2);

    Example 3(using object):

    //for object using map()


    let people =[{name:'pratiksha',age:20},

        {name:'deep',age:15},

        {name:'neel', age:16},

        {name:'meet',age:14},

        {name:'ved',age:10}];

        let obj = people.map((value,index)=>

        {

        console.log(value,index,value.name);

        return value;

        });



    // Doubling each number in the array const numbers = [1, 2, 3]; const doubled = numbers.map(function(num) { return num * 2; }); // doubled is [2, 4, 6] console.log(doubled); // Output: [2, 4, 6]

    Real Time Example :

    Ans : Applying a Discount to a List of Product Prices

    • Explanation of Syntax:
      • array: The original array that map was called upon (numbers in this case).
      • function(currentValue, index, array): A callback function that map calls on each element of array.
        • currentValue: The current element being processed in the array (num in the example).
        • index (optional): The index of the current element being processed.
        • array (optional): The array map was called upon (numbers in this case).
      • thisArg (optional): Optional. Value to use as this when executing the callback function.

    2. Filter

    • What it does: It takes an array and checks each element against a condition (specified by a function). It creates a new array containing only the elements that meet that condition.
    • Example: If you have an array of numbers [1, 2, 3, 4, 5], and you use filter with a function that checks for even numbers, you'll get [2, 4].
  • Syntax:


    let newArray = array.filter(function(currentValue, index, array) { // Return true if element passes the test }, thisArg);

    Example 1:


    // Filtering even numbers from an array const numbers = [1, 2, 3, 4, 5]; const evens = numbers.filter(function(num) { return num % 2 === 0; }); // evens is [2, 4] console.log(evens); // Output: [2, 4]

    Example 2 :
    //object for filter() let people =[{name:'Pratiksha',age:20}, {name:'Deep',age:15}, {name:'Neel', age:16}, {name:'Meet',age:14}, {name:'Ved',age:10}]; let obj = people.filter(function(age){ return age.age>15 }); console.log(obj);

    Real time example :

    Ans : Filtering Out Short Names


    • Explanation of Syntax:
      • array: The original array that filter was called upon (numbers in this case).
      • function(currentValue, index, array): A callback function that filter calls on each element of array.
        • currentValue: The current element being processed in the array (num in the example).
        • index (optional): The index of the current element being processed.
        • array (optional): The array filter was called upon (numbers in this case).
      • thisArg (optional): Optional. Value to use as this when executing the callback function.

    3. Reduce

  • What it does: It takes an array and applies a function to each element and an accumulator (which holds the result of the previous iterations). It reduces all elements of the array to a single value.
    Example: If you have an array of numbers [1, 2, 3, 4], and you use reduce with a function that adds each number to an accumulator starting from 0, you'll get 10 (which is the sum of all numbers).
    • Syntax:


    let result = array.reduce(function(accumulator, currentValue, index, array) { // Return updated accumulator }, initialValue);

    Example:


    // Summing all numbers in an array const numbers = [1, 2, 3, 4]; const sum = numbers.reduce(function(acc, current) { return acc + current; }, 0); // sum is 10 console.log(sum); // Output: 10

    Example 2 :
    //reduce for array

    let array = [2,5,8,1,2];
    let result = array.reduce((prev,current,index)=>{
        // prev= current+ index;
        console.log("prev ", prev);
        console.log("current =", current);
        console.log("Iteration ",index)
        console.log("index =" ,index);  

        return prev + current;
    },10
    );

    console.log(result);



    Real Time Example :
    Ans : Calculating the Product of a List
    • Explanation of Syntax:
      • array: The original array that reduce was called upon (numbers in this case).
      • function(accumulator, currentValue, index, array): A callback function that reduce calls on each element of array, and uses to reduce the array to a single value.
        • accumulator: The accumulated result of previous iterations.
        • currentValue: The current element being processed in the array.
        • index (optional): The index of the current element being processed.
        • array (optional): The array reduce was called upon (numbers in this case).
      • initialValue: The initial value of the accumulator (0 in this example).

    4. Sort

      • What it does: It rearranges the elements of an array in a specific order (ascending or descending) based on a compare function you provide.
      • Example: If you have an array of strings ['Banana', 'Orange', 'Apple'], and you use sort without any parameters, it will sort alphabetically, resulting in ['Apple', 'Banana', 'Orange'].

    Syntax:


    array.sort(function(firstElement, secondElement) { // Return negative value if firstElement should come before secondElement // Return positive value if firstElement should come after secondElement // Return 0 if both elements are equal });

    Example 1:


    let numbers = [4, 2, 5, 1, 3];

    let newarray2 = numbers.sort((c,d) => c-d);
    let newarray3 = numbers.sort((c,d) => d-c);


    console.log("og array=" ,numbers);
    console.log("asc",newarray2);
    console.log("desc",newarray3);

    og array= [ 5, 4, 3, 2, 1 ]

    asc [ 5, 4, 3, 2, 1 ]

    desc [ 5, 4, 3, 2, 1 ]

    Example 2:


    // Sorting an array of strings alphabetically const fruits = ['Banana', 'Orange', 'Apple']; fruits.sort(); // ['Apple', 'Banana', 'Orange'] console.log(fruits); // Output: ['Apple', 'Banana', 'Orange']

    Example 3 :
    //sot() for object let people =[{name:'Pratiksha',age:20}, {name:'Deep',age:15}, {name:'Neel', age:16}, {name:'Meet',age:14}, {name:'Ved',age:10}]; let newobj = people.sort((a,b) => a.name.localeCompare( b.name)); console.log(newobj);

    Real time example :
    Ans : Sorting Student Grades
    • Explanation of Syntax:
      • array: The array to be sorted (fruits in this case).
      • function(firstElement, secondElement): A compare function that sort uses to determine the order of elements.
        • firstElement, secondElement: The two elements being compared.
        • The function should return:
          • A negative value if firstElement should come before secondElement.
          • A positive value if firstElement should come after secondElement.
          • 0 if both elements are considered equal in terms of sorting order.

    These examples cover basic usage and syntax for each array method (map, filter, reduce, and sort) in JavaScript, demonstrating how each method can be applied to arrays to achieve different transformations and operations.

  • Use map when you need to transform elements in an array.
  • Use filter when you need to select elements based on a condition.
  • Use reduce when you need to aggregate data into a single value.
  • Use sort when you need to order elements based on certain criteria.




    • JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript.

      React JSX helps us to write HTML in JavaScript and forms the basis of React Development. Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read. 

      const element = <h1>This is sample JSX</h1>;
    • With the help of JSX, we have directly written the HTML syntax in JavaScript.

    Why JSX ?

    • It is faster than normal JavaScript.
    • It makes it easier for us to create templates.
    • Instead of separating the markup and logic in separate files, React uses components for this purpose. We will learn about components in detail in further articles.
    • As JSX is an expression, we can use it inside of if statements and for loops, assign it to variables, accept it as arguments, or return it from functions.
    Example 1 :
    // Filename - App.js

    import React from "react";

    const name = "Learner";

    const element = (
    <h1>
    Hello,
    {name}.Welcome to GeeksforGeeks.
    </h1>
    );

    ReactDOM.render(element, document.getElementById("root"));

    Example 2 :
    import React from "react";
     
    let i = 1;
     
    const element = (
        <h1>{i == 1 ? "Hello World!" : "False!"} </h1>
    );
     
    ReactDOM.render(element, document.getElementById("root"));

    Replace 
    1. class to className
    2. href = "#" to href="/"
    3. <input> to <input/>



    Props :

    1. Definition :

    • Props are like arguments you pass to a function. They are read-only and passed from a parent component to a child component.

    2. Purpose :

    • Props are used to send data and functions to child components so that the parent can control how the child behaves.
    3. Props are immutable : Once passed to a component, the component cannot change the props. They should be considered as inputs to the component.

    Example in class Component:
    import React, { Component } from 'react';

    // Child component using class
    class Greeting extends Component {
      render() {
        return (
          <div>
            <h1>Hello, {this.props.name}!</h1>
          </div>
        );
      }
    }

    // Parent component
    class App extends Component {
      render() {
        return (
          <div>
            <Greeting name="Alice" />
            <Greeting name="Bob" />
          </div>
        );
      }
    }

    export default App;

    Example in Functional Component :
    import React from 'react';

    // Child component
    const ChildComponent = (props) => {
      return <h1>Hello, {props.name}!</h1>;
    }

    // Parent component
    const ParentComponent = () => {
      return <ChildComponent name="Alice" />;
    }

    export default ParentComponent;

    State :

    Key Concepts

    1. State Initialization: State is usually initialized in the constructor for class components or directly within the function for functional components using the useState hook.
    2. State Updates: State updates are done using the setState method for class components or the setter function returned by useState in functional components.
    3. State and Re-rendering: Changing the state triggers a re-render of the component, allowing the UI to update to reflect the new state.

    1. Definition:

    • State is an object that holds information that can change over time, controlled by the component itself.

    2. Purpose:

    • State is used to manage changing data inside a component and update the UI when the data changes.
    3. State is mutable. A component can change its state using the setState method in class components or the useState hook in functional components.

    useState in Class Component :
    import React, { Component } from 'react';

    class Counter extends Component {
      constructor(props) {
        super(props);
        // Initializing state
        this.state = {
          count: 0
        };
      }

      increment = () => {
        // Updating state
        this.setState({ count: this.state.count + 1 });
      }

      render() {
        return (
          <div>
            <h1>Count: {this.state.count}</h1>
            <button onClick={this.increment}>Increment</button>
          </div>
        );
      }
    }

    export default Counter;

    useState in functional Component :
    import React, { useState } from 'react';

    const Counter = () => {
      // Initializing state using useState hook
      const [count, setCount] = useState(0);

      const increment = () => {
        // Updating state
        setCount(count + 1);
      }

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

    export default Counter;

    Toggle Example using state :

    import React ,{useState}from 'react'


    export default function Onoff() {
        let[ison,setIson]= useState(false);

        let toggle=()=>{
            
    console.log("clicked")
    setIson(!ison);

    if(ison){
        window.alert("button on");
    }else{
        window.alert("button off");
    };
        }
      return (
        <div>
          <button style={{color:'black',backgroundColor:ison?'red':'white'}} onClick={toggle}  >{ison ? "On":"Off"}</button>
          {/* {ison ? "On":"Off"} */}

        </div>
      )
    }


    Add input and make a list usind map():


    import React, { useState } from 'react';

    function Input() {
      const [text, setText] = useState('');
      const [inputList, setInputList] = useState([]);

      const handleInputChange = (e) => {
        setText(e.target.value);
      };

      const handleInputSubmit = () => {
        if (text.trim() !== '') {
          setInputList([...inputList, text]);
          setText('');
        }
      };

      const handleDelete = (index) => {
        const newList = [...inputList];
        newList.splice(index, 1);
        setInputList(newList);
      };

      return (
        <div>
          <input type="text" value={text} onChange={handleInputChange} />
          <button type='button' onClick={handleInputSubmit}>Submit</button>
          <div>
            <h2>Entered Texts:</h2>
            <ul>
              {inputList.map((item, index) => (
                <li key={index}>
                  {item}
                  <button onClick={() => handleDelete(index)}>Delete</button>
                </li>
              ))}
            </ul>
          </div>
        </div>
      );
    }

    export default Input;

    {inputValue.map((item, index)=>(
    <li key={index}>
    {item}




    Controlled and Uncontrolled Components :

    Controlled Component

    • The component’s value is controlled by React state.
    • You handle the input value using useState or this.state.
    • React is in full control of the input.

    Example:

    import React, { useState } from "react";
    const ControlledComponent = () => { const [value, setValue] = useState(""); // React controls the value const handleChange = (event) => { setValue(event.target.value); //Update state when input changes }; return ( <div> <input type="text" value={value} onChange={handleChange} /> {/* React state controls this */} <p>Input Value: {value}</p> </div> ); }; export default ControlledComponent;

    Uncontrolled Component

    • The component’s value is managed by the DOM itself.
    • You access the value using a ref (reference to the input).
    • React does not directly control the input value.

    Example:


    import React, { useRef } from "react"; const UncontrolledComponent = () => { const inputRef = useRef(null); // Reference to the input const handleSubmit = () => { alert(`Input Value: ${inputRef.current.value}`); // Access DOM value }; return ( <div> <input type="text" ref={inputRef} /> {/* DOM controls this */} <button onClick={handleSubmit}>Submit</button> </div> ); }; export default UncontrolledComponent;

    Key Differences

    FeatureControlled ComponentUncontrolled Component
    ControlValue is managed by React stateValue is managed by the DOM
    Access ValueUse value and onChangeUse ref to get value directly
    When to UseWhen React needs full control of the input (e.g., validations, dynamic UI updates).For simple forms where React doesn’t need to track every keystroke.

    Which to use?

    • Controlled Components: Preferred for most cases as they provide better control and are easier to debug.
    • Uncontrolled Components: Useful for quick forms where managing state isn’t necessary

    Let’s dive a little deeper into each React hook but still keep it simple for better understanding:


    1. useState

    • What does it do?
      useState is used to add state (data that changes over time) to a functional component. Whenever the state changes, the component re-renders to show the updated value.

    • How it works?
      You call useState(initialValue), which gives you:

      • A state variable to hold the current value.
      • A function to update the state.
    • Example:

      import React, { useState } from "react";
      const Counter = () => { const [count, setCount] = useState(0); // count starts at 0 const increment = () => setCount(count + 1); // Updates the state return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increase</button> </div> ); };

    2. useEffect

    • What does it do?
      It lets you perform side effects in your component, like:

      • Fetching data from an API.
      • Subscribing to events.
      • Setting up a timer.
    • When does it run?

      • By default, it runs after every render.
      • You can control when it runs by passing dependencies (a list of variables it should "watch") as the second argument.
    • Example:

      import React, { useState, useEffect } from "react";
      const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch("https://api.example.com/data") .then((response) => response.json()) .then((data) => setData(data)); }, []); // Runs only once after the component mounts return <p>Data: {data ? JSON.stringify(data) : "Loading..."}</p>; };

      How useEffect Works with Dependencies

      1. Default Behavior (No Dependencies Provided):
        • useEffect runs after every render (both initial and re-renders).
        • Example:
          import React, { useState, useEffect } from "react";
          const Counter = () => { const [count, setCount] = useState(0); useEffect(() => { console.log("useEffect runs after every render"); }); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }; export default Counter;
        • In this example, useEffect runs every time the Counter component renders (when count is updated).

      1. Empty Dependency Array ([]):
        • useEffect runs only once, after the initial render.
        • Use this when you want to do something only when the component mounts, like fetching data or setting up a timer.
        • Example:
          import React, { useState, useEffect } from "react";
          const Timer = () => { const [time, setTime] = useState(0); useEffect(() => { const interval = setInterval(() => { setTime((prevTime) => prevTime + 1); }, 1000); return () => { clearInterval(interval); // Clean up when the component unmounts }; }, []); // Runs only on mount return <p>Timer: {time} seconds</p>; }; export default Timer;
        • The [] ensures the timer starts only once when the component mounts.

      1. With Dependencies ([dep1dep2, ...]):
        • useEffect runs only when one or more of the dependencies change.
        • Use this when the effect depends on specific variables.
        • Example:
          import React, { useState, useEffect } from "react";
          const NameDisplay = () => { const [name, setName] = useState(""); const [message, setMessage] = useState(""); useEffect(() => { console.log("Effect runs because 'name' changed"); setMessage(`Hello, ${name}`); }, [name]); // Only runs when 'name' changes return ( <div> <input type="text" placeholder="Enter your name" value={name} onChange={(e) => setName(e.target.value)} /> <p>{message}</p> </div> ); }; export default NameDisplay;
        • Here, the effect runs whenever the name state changes, updating the message.

      1. No Dependencies (Running Unintentionally on Every Render):
        • Be careful not to omit the dependency array if you don’t intend the effect to run on every render. This can lead to unnecessary operations.
        • Example of an unintended mistake:
          useEffect(() => {
          console.log("This runs after every render, which may not be needed."); }); // No dependencies provided

      Cleanup in useEffect

      • If your effect creates something like a timer, subscription, or event listener, React recommends cleaning it up to prevent memory leaks.

      • Cleanup is done by returning a function inside useEffect.

      • Example with cleanup:

        import React, { useState, useEffect } from "react";
        const MouseTracker = () => { const [position, setPosition] = useState({ x: 0, y: 0 }); useEffect(() => { const handleMouseMove = (event) => { setPosition({ x: event.clientX, y: event.clientY }); }; window.addEventListener("mousemove", handleMouseMove); // Cleanup function to remove the event listener when the component unmounts return () => { console.log("Cleanup - removing event listener"); window.removeEventListener("mousemove", handleMouseMove); }; }, []); // Runs only on mount return ( <div> <p>Mouse Position: {`X: ${position.x}, Y: ${position.y}`}</p> </div> ); }; export default MouseTracker;

      Summary of useEffect Dependency Array

      Dependency ArrayWhen Does useEffect Run?Use Case
      No dependency arrayAfter every render (initial + updates).Running something every time the component renders.
      []Once after the initial render (on mount).Initial setup like fetching data or starting a timer.
      [dep1, dep2, ...]When any dependency in the array changes.Reacting to changes in specific variables.



    3. useContext

    • What does it do?
      It lets you access data from a context, which is a way to pass values (like theme or user info) to deeply nested components without props.

    • How it works?
      You create a Context and use useContext to consume its values.

    • Example:

      import React, { createContext, useContext } from "react";
      const UserContext = createContext(); const UserInfo = () => { const user = useContext(UserContext); // Get the value from context return <p>Username: {user}</p>; }; const App = () => { return ( <UserContext.Provider value="Anjali"> <UserInfo /> </UserContext.Provider> ); }; export default App;

    4. useRef

    • What does it do?
      useRef is a React hook that allows you to access a DOM element directly or store a value that doesn’t cause the component to re-render when updated.

    • Example Use Cases:

      • Focusing an input field.
      • Storing a mutable value (like a counter) that doesn’t affect rendering.
    • Example:

      import React, { useRef } from "react";
      const FocusInput = () => { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); // Access the input element }; return ( <div> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus Input</button> </div> ); }; export default FocusInput;

      Why Use useRef Instead of State?

      • State: Causes re-renders when updated, which is unnecessary if all you want is to perform an action like focusing on an element.
      • useRef: Allows you to perform DOM actions or store values without affecting rendering.

    5. useReducer

    • What does it do?
      It manages more complex state logic compared to useState. Think of it as a mini Redux for a single component.

    • How it works?

      • You define a reducer function that takes the current state and an action, then returns the updated state.
      • useReducer gives you the state and a dispatch function to trigger actions.
    • Example:

      import React, { useReducer } from "react";
      const reducer = (state, action) => { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, { count: 0 }); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> </div> ); }; export default Counter;

    6. useMemo

    • What does it do?
      useMemo is a React hook that memoizes(remember) the result of a computation to improve performance. It prevents expensive calculations from being recalculate unnecessarily during re-renders.

    • It avoids recalculating values for every re-render unless the dependencies change.

      Why Use useMemo?

      1. Performance Optimization:

        • It avoids recalculating values for every re-render unless the dependencies change.
        • Useful when dealing with expensive operations like filtering, sorting, or performing heavy computations.
      2. Prevents Wasted Work:

        • React re-renders components when their state or props change. If a component includes expensive computations, these can be avoided using useMemo.

    Without useMemo:

    In this example, we calculate the square of a number whenever the parent component re-renders:

    import React, { useState } from "react";
    const ExpensiveCalculation = ({ number }) => { console.log("Calculating square..."); const square = number * number; return <div>Square of {number} is {square}</div>; }; const Parent = () => { const [count, setCount] = useState(0); const [number, setNumber] = useState(2); return ( <div> <button onClick={() => setCount(count + 1)}>Increment Count ({count})</button> <button onClick={() => setNumber(number + 1)}>Change Number ({number})</button> <ExpensiveCalculation number={number} /> </div> ); }; export default Parent;

    What's the Issue?

    • Every time you click Increment Count, the Parent component re-renders.
    • Even though number hasn't changed, the square is recalculated, which is unnecessary.

    With useMemo:

    import React, { useState, useMemo } from "react";
    const ExpensiveCalculation = ({ number }) => { const square = useMemo(() => { console.log("Calculating square..."); return number * number; }, [number]); // Only recalculate if `number` changes return <div>Square of {number} is {square}</div>; }; const Parent = () => { const [count, setCount] = useState(0); const [number, setNumber] = useState(2); return ( <div> <button onClick={() => setCount(count + 1)}>Increment Count ({count})</button> <button onClick={() => setNumber(number + 1)}>Change Number ({number})</button> <ExpensiveCalculation number={number} /> </div> ); };  

    export default Parent;

    7. useCallback

    • What does it do?
      Memoizes a function, so it doesn’t get re-created every time the component re-renders. This prevents unnecessary renders in child components.

    • Example:

      import React, { useState, useCallback } from "react";
      const Child = React.memo(({ onClick }) => { console.log("Child rendered"); return <button onClick={onClick}>Click Me</button>; }); const App = () => { const [count, setCount] = useState(0); const handleClick = useCallback(() => { console.log("Button clicked"); }, []); // Memoized function return ( <div> <Child onClick={handleClick} /> <button onClick={() => setCount(count + 1)}>Increment Parent</button> </div> ); }; export default App;

      Key Differences:

      useMemouseCallback
      Memoizes the result of a calculation or value.Memoizes the function itself.
      Useful for expensive calculations or complex values.Useful for functions that don’t need to be recreated on every render.
      Returns a value (e.g., calculation result).Returns a function (e.g., event handler).
      Example: Calculating a factorial or sorting a list.Example: Preventing a function from being re-created and passed to child components.

    8. useLayoutEffect

    • What does it do?
      It’s like useEffect but runs synchronously before the browser updates the screen. Use it for DOM measurements or animations.

    • Example:

      import React, { useRef, useLayoutEffect } from "react";
      const Box = () => { const boxRef = useRef(); useLayoutEffect(() => { boxRef.current.style.width = "200px"; // Runs before UI is painted }); return <div ref={boxRef} style={{ height: "100px", backgroundColor: "blue" }}></div>; }; export default Box;

    useRefuseMemo
    Keeps track of values or DOM references without re-rendering.Memorizes results of calculations to avoid recomputing.
    Used for focusing inputs, tracking values (like counters).Used for expensive calculations, like factorials or sorting.


    Comments

    Popular posts from this blog

    Introduction To Java

    ReactJs Interview Questions