React

What is React?

  • It is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications.

  • Many people mistook it for a JavaScript Framework.

  • React was created and is maintained by Facebook (now Meta). It was made to develop the UI (User Interface) of a web application.

Why Should We Use React?

  1. React is a component-based architecture library. That means we can create a chunk of code for a UI that looks the same but has different data inside the UI.

  2. Reacts reusable components are blocks of code that can be written once and reused in different parts of the projects.

  3. Virtual DOM (Document Object Model) is a feature of React. It creates a copy of the original DOM. Whenever the state of the application changes, the virtual DOM catches those changes, compares them to the original DOM, and then implements the changes to the original DOM.

  4. JSX (JavaScript XML) is a mixture syntax of JavaScript and XML. It allows us to write HTML inside JavaScript in a much simpler and efficient way.

  5. React has a large community of support. There are many React libraries available for various use cases which were developed by many developers

  6. React uses a unidirectional data flow. Which means data can flow in only one direction. In the case of React, data flows downwards (parent components to child components).

  7. React can also be used for Mobile app development. That version of React is known as React Native.

Differences between Framework and Library?

Framework
Library

A framework provides a structured foundation upon which software developers can build programs for a specific platform. It offers a predefined architecture and controls the flow of the application, guiding the developer through the process

A library is a collection of pre-written code that developers can use to perform specific tasks or operations

A framework dictates the flow and structure of your application. It calls your code at predefined points, rather than you are calling its code.

A library is a collection of functions and utilities that you can call directly to perform specific tasks. The control remains with the developer.

Frameworks offer a full structure for applications

Libraries offer specific functionalities.

Frameworks control the flow of the application

Libraries provide utilities that you call

Frameworks enforce certain patterns and structures.

Libraries offer more flexibility in how they are used

Frameworks generally require more time to learn

Libraries can be easier to pick up and integrate.

Frameworks require extensive code for their structure and functionality

Building a library typically requires less code.

AngularJS, Spring, and NodeJS, offer comprehensive solutions for building applications, providing a structured environment for development

jQuery and React JS, which provide specific functionalities that developers can incorporate into their projects

Can web browsers read JSX directly?

  • Web browsers cannot read JSX directly. This is because they are built to only read regular JS objects and JSX is not a regular JavaScript object

  • For a web browser to read a JSX file, the file needs to be transformed into a regular JavaScript object. For this, we use Babel

What is the Virtual DOM? why better than Real DOM?

DOM stands for Document Object Model. The DOM represents an HTML document with a logical tree structure. Each branch of the tree ends in a node, and each node contains objects.

virtualdom

React keeps a lightweight representation of the real DOM in the memory, and that is known as the virtual DOM. When the state of an object changes, the virtual DOM changes only that object in the real DOM, rather than updating all the objects.

In Real DOM, when an object changes in DOM tree its updates all the objects again once rather than updating the changed object only. In React it uses Virtual DOM means keeping a copy version of real DOM. Here the advantages are now when any value changes it rather than updating all the objects it only updates the changed value only making the process much faster.

real-Dom

What is Component? What are the components in React?

Components are the building blocks of any React application, and a single app usually consists of multiple components. A component is essentially a piece of the user interface. It splits the user interface into independent, reusable parts that can be processed separately.

There are two types of components in React:

react-component
  • Functional Components: These types of components have no state of their own and only contain render methods, and therefore are also called stateless components. They may derive data from other components as props (properties).

function Greeting(props) {
  return <h1>Welcome to {props.name}</h1>;
}
  • Class Components: These types of components can hold and manage their own state and have a separate render method to return JSX on the screen. They are also called Stateful components as they can have a state.

class Greeting extends React.Component {
  render() {
    return <h1>Welcome to {this.props.name}</h1>;
  }
}

What are the differences between state and props?

State

Props

Use

Holds information about the components

Allows to pass data from one component to other components as an argument

Class vs Functionality

Use in Class

use in Functional

Mutability

Is mutable

Are immutable

Read-Only

Can be changed

Are read-only

Child components

Child components cannot access

Child component can access

Stateless components

Cannot have state

Can have props

What is a “module” in React? Why do you use modules in your code?

Modules

Definition: A module is a piece of code (a file) that encapsulates functionality which can be reused in different parts of an application. This functionality can be anything from utility functions, classes, constants, or even React components.

Purpose: Modules help organize code into logical and reusable parts, making the codebase easier to manage and understand.

Components

Definition: A component in React is a self-contained piece of the user interface (UI) that can manage its own state and lifecycle. Components are the building blocks of a React application's UI.

Purpose: Components define the structure, behavior, and appearance of a part of the user interface. They allow for the creation of complex UIs from small, isolated, and reusable pieces.

Key Differences

  1. Scope and Usage:

    • Module: A file that can contain any kind of code. It is not specific to the UI but can include functions, classes, constants, and React components. Modules can be imported and used anywhere in the application.

    • Component: Specifically a part of the UI. It is a JavaScript function or class that optionally accepts inputs (props) and returns a React element that describes how a section of the UI should appear. Components are used to construct the UI.

  2. Content:

    • Module: Can include anything from utility functions, constants, classes, or other code that is not directly related to rendering the UI.

    • Component: Specifically focused on rendering UI and handling user interactions. It can be a function or a class that returns JSX.

Example to Illustrate the Difference

Let's use a simple example: a counter application.

1. Utility Module

This module contains utility functions to increment and decrement a counter.

// utils.js (Utility Module)
export function increment(value) {
  return value + 1;
}

export function decrement(value) {
  return value - 1;
}

2. Counter Component

This component uses the utility functions from the module to update its state.

// Counter.js (Component)
import React, { useState } from 'react';
import { increment, decrement } from './utils'; // Importing functions from the module

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(increment(count))}>Increment</button>
      <button onClick={() => setCount(decrement(count))}>Decrement</button>
    </div>
  );
}

export default Counter;

3. App Component

This component uses the Counter component to display the counter in the application.

// App.js (Component)
import React from 'react';
import Counter from './Counter'; // Importing the Counter component

function App() {
  return (
    <div>
      <h1>My Counter App</h1>
      <Counter />
    </div>
  );
}

export default App;

Summary

  • Modules:

    • Used for organizing code logically.

    • Can contain any type of code, such as utility functions, classes, constants, and components.

    • Example: utils.js containing utility functions increment and decrement.

  • Components:

    • Used for building the UI.

    • Encapsulate UI logic, state, and rendering.

    • Example: Counter.js containing a React component that displays and updates a counter.

Module Vs Component in React?

Module
Component

Modules focus on the structural organization of code, grouping related functionalities together to enhance code management and maintainability.

Components are more focused on the functional aspect of the application, specifically on rendering views and handling user interactions.

Module: A file that exports code (functions, objects, classes) which can be imported elsewhere.

Component: A self-contained piece of the UI in React, defined as either a function or a class.Components can be used in other components or parts of the application, such as in App.js.

Modules play a crucial role in organizing and structuring the codebase

Components are the building blocks for UI elements

A collection of related functionalities, typically grouping multiple components and other features.

A single, reusable piece of the UI, encapsulating its own structure and behavior.

Manages and organizes the overall structure and dependencies of an application or a part of it.

Manages a specific part of the UI and its logic.

Module do not have states

Components can manage their own state and receive data via props.

Module don't have types

Functional components (stateless) and class components (stateful)

Each Module is independent

Components can interact with other components or services, enabling dynamic behavior

Example of a Module

A module can export functions, variables, or classes that can be imported and used in other parts of your application. Here's a simple example:

utils.js (Module)

// This is a module that exports a utility function
export function formatDate(date) {
    return new Date(date).toLocaleDateString();
}

AnotherModule.js (Using the Module)

// This module imports the utility function from utils.js
import { formatDate } from './utils';

const date = '2023-06-20';
console.log(formatDate(date)); // Outputs formatted date

Example of a Component

A component is a class or a function that optionally takes inputs (called "props") and returns a React element that describes how a section of the UI should appear.

Functional Component

MyComponent.js

import React from 'react';

// A functional component
function MyComponent({ name }) {
    return (
        <div>
            <h1>Hello, {name}!</h1>
        </div>
    );
}

export default MyComponent;

Class Component

MyClassComponent.js

import React, { Component } from 'react';

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

export default MyClassComponent;

Using the Component

You can import and use these components in another file:

App.js

import React from 'react';
import MyComponent from './MyComponent';
import MyClassComponent from './MyClassComponent';

function App() {
    return (
        <div>
            <MyComponent name="Alice" />
            <MyClassComponent name="Bob" />
        </div>
    );
}

export default App;

Summary

  • Module: A file that exports code (functions, objects, classes) which can be imported elsewhere. Example: utils.js exporting a formatDate function.

  • Component: A self-contained piece of the UI in React, defined as either a function or a class. Example: MyComponent.js and MyClassComponent.js. Components can be used in other components or parts of the application, such as in App.js.

Where do you use Module in Your Code ?

Why do you export and import a component?

  1. Components can be reused across different parts of the application. By exporting a component, you make it available for import and use in other components or files, promoting DRY (Don't Repeat Yourself) principles.

  2. Changes to a component or module are localized. If you need to update a component, you can do so in one place without affecting other parts of the application directly.

  3. In a team environment, different developers can work on different components or modules simultaneously without conflicts.

  4. Summary:

    • Exporting: Makes a component available to other files. You can export components using default or named exports.

    • Importing: Brings in exported components or modules into a file where they are needed


To Change Web application data real-time, Which React property you will use?

To change web application data in real-time, you would use Reacts state property. The state is a built-in object in React components that is used to store data that can change over time. It allows your component to react and update its output when the state changes.

In functional components, state is initialized using the useState hook.

What is useState()?

The useState hook is a function that lets you add state variables to your functional components. When you call it, you pass the initial state, and it returns an array containing two elements:

  1. The current state value.

  2. A function to update the state value.

Syntax

const [state, setState] = useState(initialState);

Example and Explanation

Here's a simple example of how to use useState:

import React, { useState } from 'react';

const Counter = () => {
  // Declare a state variable named "count" with an initial value of 0
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
};

export default Counter;

Detailed Explanation

  1. Declare State Variable:

    const [count, setCount] = useState(0);
    • count is the state variable.

    • setCount is the function to update the state.

    • 0 is the initial state value.

  2. Using the State Variable:

    <p>You clicked {count} times</p>
    • The current value of count is displayed.

  3. Updating the State:

    <button onClick={() => setCount(count + 1)}>
      Click me
    </button>
    • When the button is clicked, setCount is called with count + 1, updating the state and causing the component to re-render with the new value.

Where to Use useState()

Use useState whenever you need to add state to a functional component. Here are some common scenarios:

  1. Counter or Toggle States:

    • Implementing a counter, like in the example above.

    • Managing toggle states, such as showing/hiding elements.

  2. Form Inputs:

    • Managing form input values (e.g., text fields, checkboxes).

    const [name, setName] = useState('');
    
    return (
      <input 
        type="text" 
        value={name} 
        onChange={(e) => setName(e.target.value)} 
      />
    );
  3. API Data:

    • Storing data fetched from an API.

    const [data, setData] = useState(null);
    
    useEffect(() => {
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => setData(data));
    }, []);
  4. UI State:

    • Managing various UI states, such as modal visibility, active tabs, etc.

    const [isModalOpen, setIsModalOpen] = useState(false);
    
    return (
      <div>
        <button onClick={() => setIsModalOpen(true)}>Open Modal</button>
        {isModalOpen && <Modal onClose={() => setIsModalOpen(false)} />}
      </div>
    );

Key Points

  • Initial State: The argument passed to useState is the initial state value.

  • State Setter Function: The function returned by useState is used to update the state.

  • Re-render: Updating the state causes the component to re-render with the new state.

Wha is useEffect()

useEffect is a hook in React that allows you to perform side effects in functional components. Side effects include tasks like fetching data, directly manipulating the DOM, setting up subscriptions, and cleaning up resources.

Passing an Empty Array ([]) to useEffect

When you pass an empty array as the dependency array to useEffect, like this:

const [data, setData] = useState(null);

useEffect(() => {
    console.log('Fetching data...');
    fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => setData(data));
  }, []); // Empty array means this runs only once when the component mounts
  • Effect Execution: The effect runs only once, after the initial render.

  • Subsequent Renders: The effect will not run again on subsequent renders.

This is useful for running code that you only want to execute once, such as initializing data when the component mounts.

Passing Dependencies to useEffect

When you pass an array of dependencies to useEffect, like this:

const CounterComponent = () => {
  const [counter, setCounter] = useState(0);

  useEffect(() => {
    console.log('Counter changed:', counter);
    // Any effect logic that depends on `counter`

    return () => {
      console.log('Cleanup for counter:', counter);
      // Any cleanup logic for when `counter` changes or component unmounts
    };
  }, [counter]); // Effect runs when `counter` changes

  return (
    <div>
      <h1>Counter: {counter}</h1>
      <button onClick={() => setCounter(counter + 1)}>Increment</button>
    </div>
  );
};
  • Effect Execution: The effect runs after the initial render and whenever any of the dependencies in the array change.

  • Dependencies: React compares each dependency in the array using the Object.is comparison algorithm. If any dependency has changed since the last render, the effect will run again.

This is useful for responding to changes in specific state or props.

Not Passing a Dependency Array

When you don't pass a dependency array to useEffect, like this:

  useEffect(() => {
    console.log('Component rendered or updated');

    return () => {
      console.log('Cleanup before next render or unmount');
    };
  }); // No dependency array means this runs after every render
  • Effect Execution: The effect runs after every render, both the initial render and all subsequent re-renders.

This example logs a message every time the component renders:

Summary

  • Empty Array ([]): Effect runs once after the initial render. Useful for one-time setup actions.

  • Dependencies ([dependency1, dependency2, ...]): Effect runs after initial render and whenever any dependency changes. Useful for responding to changes in specific state or props.

  • No Dependency Array: Effect runs after every render. Useful for actions that need to occur every time the component updates.

Grid vs Flexbox

Grid:

  • Designed for 2-dimensional layout (both rows and columns).

  • Allows you to layout items into rows and columns.

  • More powerful for creating complex layouts.

Flexbox:

  • Designed for 1-dimensional layout (either row or column).

  • Great for distributing space along a single dimension.

  • Useful for aligning items and distributing space within a container.

Comparison:

  • Use Grid when you need a layout in both dimensions, e.g., complex web pages.

  • Use Flexbox when you need a layout in a single dimension, e.g., navigation bars, alignment of items.

Last updated