Reactjs Tutorial

For Beginners To Experts


Reactjs Tutorial

What is React

  • It is a JavaScript Library (not a framenwork) for creating interfaces (UIs).
  • It is used to make reusable UI components
  • It is created and maintained by Facebook that is based on components.
  • It is an open source declarative Javascript library.
  • We can make small UIs then combine all together to make a complex single interface(UI).
  • It create virtual DOM in memory which is a representation of the web browser's DOM.
  • It uses the virtual DOM which is faster than real DOM and makes the performance of our app higher.
  • It uses components and data pattern.
  • It was developed by Facebook in 2011.
  • Initial public release version is V0.3.0 was in May 2013.
  • Latest version is V18.0.0 that released in Aprill 2022.
  • It can be used on client and server-side.
  • It can be used for view layer of our app.
  • It was created by Jordan Walke a software engineer at Facebook company.
  • A ReactJS application is made up of many components
  • A React component responsible for displaying a small part of our app.
  • Small components can be nested or combined with other components to make a complex app.
  • React changes or updates what is to be updated, It is not updating the whole app that reduce the performance.
  • It changes a single DOM element instead of update or reload the whole DOM.
  • As an example, think of a webpage, the top navbar is a component, the left side bar is another component and the footer is the other components too. When we combined all three together it will create a webpage. All component are separate from each other and are reusable, any changes or any modifications to any of them, will update that component only which increase performance of our app.
  • React getting more popularity in the front-end, due to using features such as:
    High performance due to using virtual DOM built automatically in the memory than browsers' real DOM
    using JSX(JavaScript syntax extension which is an XML or HTML like syntax used by ReactJS for simplicity)
    Components (the functions in a separate file that do one job and are reusable)
    One-way Data Binding (data flows from parent to child - one way in Virtual DOM)
  • React is used only for the UI Layers of the app(view layers of the application).

Note:

What is declarative?

  • We tell React what to do, it will do it for us.
  • We do not need to tell the steps to do for us.
  • For example: We tell react to cook pasta for us, it will do it for us.
  • we do not need to tell the steps or instruction to make pasta for us.

Two ways to install React

  • Using command create-react-appto install necessary tools and modules automatically
  • Using Command npm to install packages and modules manually

First way of react installation using create-react-app

This command is a tool which install transpiling webpack and babel for us.

Babel transpiles ES6 to ES5 (jsx to javascript) to be readable by browsers.

JSX is JavaScript XML.

Install NodeJS and NPM platforms (package managers)

  • These package managers are necessary for developing ReactJS application.
  • Install NodeJS that comes with npm from nodejs.org.
  • First have a code editor such as visual studio code (vscode). You can download it from code.visualstudio.com
  • Create a folder on desktop.
  • Right click the folder open it with vscode
  • Open terminal in vscode by pressing shift+Ctrl+`on the keyboard.
  • Install React by type in the terminal the command npm install -g create-react-app (-g means install globally and installation must be in the root directory ie. main folder of react app we are making).
  • After installation of React , we can use create-react-app tool to create a React project. We name it first-app. Use the command create-react-app first-app in the terminal to create the React project with the name of first-app.
  • We can usenpx create-react-app first-app command to install React and React project at the same time. npx is a package runner tool that comes with npm 5.2 and above.

After the installation we have the following React structure folders

React Folders and Files Structure

node_modules folder
This directory or folder contains the whole React dependencies packages for building and running React project.
It includes React and other libraries such as third parties libraries. They are react , react-dom , dependencies of packages which are needed (transitive ones), such as ESLint, babal, webpack etc.

babel needed to convert JSX to JavaScript, ESlint for formating the codes and webpack for converting html and css with the help of a loader to modules.
webpack only knows about json and javascript files.
public folder
It holds all assets such as images, Javascript libraries and static files like index.html(mount the app by default) that we do not want to be processed by webpack.
src folder
It contains dynamic Javascript file that are needed to be processed by webpack.These files are:
The App.css, App.js, App.test.js, index.css, index.js, and serviceWorker.js.
.git folder
It includes information and history of the project.
The information includes repository address, commits, changes information for rolling back and so on.
By default is is hidden to prevent from deletion.
Some of folders and files in the .git folder are:
hooks: This folder includes script files that are executed before or after events.
objects: This folder display Git database object.
config: This file is local configuration file.
refs: This folder contains and keeps branches data and tags.
HEAD: This file keeps a reference to the current branch(by default to master branch) .
index: This file stores staging data (a binary file).
package.json:
It is a metadata for npm(package manager) to handle and configure project and its dependencies.
package-lock.json file
This file locks down the dependencies versions till the project always use the same versions.
When a package is installed, it is automatically created by npm.
It records the versions of all dependencies and its sub-dependencies when npm install any packages.
README.md file
This file includes basic information about the project such as:
It is a documentation about React
What the project is about.
Displaying the look of the project by an image.
Running and using instructions of the project.
Any other relevant information.
.gitignore file
This file allows Git to ignore some files like the following:
node_modules/ (big unnecessary files for Git server)
.cache/ (bundlers' temporary cache files)
dist/ (stores the build process output)
.env (it is a secure environmnet for values and variables that must not be shared)
.DS_Store (this file stores custom attributes of any visual information such as icon and so on)
coverage/ (it is a code coverage testing)
.vscode/ (stores project settings created by vscode - specific ones)

The src folder contains the following files.

App.css
This file styles the React App or the Components.
It is the first loaded root or top component that loads all other css files which is written in it.
App.js
This file is a container for all other components, combine all other components, it is as DOM Node or main page. It wrapes all other components
App.test.js
This file is used for mounting components to make sure that they didn't throw during rendering.
index.css
It will style the index.js file in the same directory or folder.
index.js
This file is the place where you mount(render) the whole react component (all components combined in this file) onto root element.
Index.js is the first file searched for in that directory, when adding an ES6 import statement.
logo.svg
It is the logo of react shown in web browser.
serviceWorker.js
This file is added to React build by default.
It is a script that runs in the browser's background, for usage of features that do not need users' interaction.

Run the app in browser by typing in terminal use the command npm start . It will show the default app we created in the browser on port 3000.

If you change the contents of the App.js file in the src folder, you will see the changes in browser on port 3000.

App.js is the root of our app that combine all components together. Then we connect App.js to index.js to show our app in the index.html file to view in browser.

To run the server in the browser by npm startcommand, we must be at the root folder I mean the main folder of our app. If not use the command cd first-app to go to root folder then type the command in terminal.

Second way of React installation using npm

To install packages and modules manually

  • Install nodejs that comes with npm packages from nodejs.org .
  • Create a folder on desktop name it reactApp
  • right click reactApp folder, open it with vs code.
  • Now we are in the root folder (reactApp)
  • Now in terminal type in npm -init -y to create a file named package.json for handling and creating any modules we are creating.
  • After creation of package.json, we create react and react Dom package by typing in terminal npm install react react-dom --save
  • We can install react and react-dom separately if you want. npm install react --save and npm install react-dom --save

Install Webpack

It is used for module packaging, development and production.

Webpack bundles webpack-dev-server for development, webpack for production and webpack CLI that contains necessary commands to be used in command prompt or terminal.

Use the command npm install webpack webpack-dev-server webpack-cli --save to install all three at one time

Instal Babel

babel is a JavaScript compiler that convert JSX into javascript to be readable by browsers.

  • To install Babel we have to have the following codes in terminal typed npm install babel-core babel-loader babel-preset-env babel-preset-react babel-webpack-plugin --save dev

    babel-loader is for jsx files, babel-preset-react is for updating browsers automatically and ES6 uses babel-preset-env

  • Then we add the following files in our folder.
  • index.html
  • App.js
  • index.js
  • webpack.config.js
  • .babelrc

webpack.config.js is used to configure webpack, it is the entry point of our app, it sets the development port, it adds plugins and loaders for different file types.

Add the following codes to configure webpack in webpack.config.json

  • Now in scripts object of package.json file replace the following codes.
  • Now add the following code in index.html file.

    Now we are importing the script source file of index_bundel.js into index.html file to Use fileHtmlWeb-packPlugin plugin from bundeled file which scale our app to be responsive to differnt devices.

    App.js

    It is entry point of our app to render our components

    Add the following code into App.js.

    Now we import App.jsfile (component) into root directory (index.js) file.

    Run the server and see the result by typing in terminal the command npm start

    Now you can create a bundled file named index_bundle.js which bundle all file into a file and merge them to have it with other files of webpage to load the app at once. For bundeling type the command npm run build in terminal to merge the file into one file (index_bundle.js).

    Note:

    • NPM is a package manager.
    • NPM starts the default server at localhost:3000in your browser.
    • 3000 is the port number.
    • Webpack, Babel and etc., are dependencies in React.
    • create-react-appis a tool that wrap all dependencies for react.
    • npm -v and nodejs -v will show the version number of package managers.
    • To use create-react-app we have to have Node version 8.10 and NPM version 5.6 and above.
    • Use cd + directory name to go to desired directory or folder.
    • DOM is a cross-platform dealing with HTML, XML or XHTML
    • The virtual Dom compare the previous and new changes in the DOM and then the Real DOM(browser's Dom) update only the changes, not the whole website or app. This makes the app faster.

    What is Difference between ReactJS and React Native?

    ReactJS: Focused on web development, ReactJS facilitates the creation and management of dynamic user interfaces for web pages and applications. It runs directly in web browsers, allowing developers to craft engaging and interactive UIs utilizing JavaScript.

    React Native is expressly crafted for the development of mobile applications, empowering the generation of native applications for mobile devices through the utilization of JavaScript and React. Its focus extends to mobile operating systems like iOS and Android, facilitating a cohesive codebase for both platforms.

    ReactJS ses CSS for styling, which can be applied through external stylesheets, inline styles, or CSS-in-JS libraries. React Native: Employs a styling system that resembles CSS but actually uses JavaScript objects to style components. This approach is more in line with how React itself handles UI logic.

    • React components are the building blocks of a user interface.
    • They are reusable and modular pieces of code.
    • They encapsulate specific function or UI(user interface) elements.
    • They break down UI into smaller, manageable parts.
    • They make our UI much more easier to develop,maintain, troubleshoot, and understand.

    There are two types of components in React:

    Functional Components:

    • Functional Components are simpler and stateless components that are essentially JavaScript functions.
    • They take in props as parameters and return React elements.
    • Functional components are used for UI elements when you don't need to manage state.

    Example 1: Using jsx (Javascript and XML)
    Functional Component without Props


    Example 2:
    Functional Component with Props


    Example 3:
    Functional Component with Destructuring Props


    Class Components:

    • React class components are ES6 classes that extend from React.Component.
    • They contain and control local state.
    • They are suitable for more complex components.
    • With the use of Hooks in React 16.8, functional components can manage state using the useState hook.
    • Experimenting with hooks can greatly improve performance, readability, and maintainability.

    Example 1:
    Class Component without State


    Example 2:
    Class Component with State


    Example 3:
    Class Component with Lifecycle Method


    Props:

    • Prop is short term for property.
    • They pass data from parent components to child components.
    • Props are read only, means the child components that are receiving props can not modify the value of it.

    Parent and child component are usually in separate .js or .jsx file

    Parent component or file collects all child components in one place or file.

    Each child components are written in a separate .js files


    Example 1:
    Functional Component without Props


    Example 2:
    Functional Component with Props


    Example 3:
    Class Component with Props and State


    States

    • State refers to a JavaScript object that depicts the present condition or data within a component.
    • state is confined within the component (internal) to the component and can be changed and modified (mutable) by the component itself (Unlike the props that could not be modified by child components).
    • State changes trigger re-rendering, and update data of that part or section of user interface (that components only).

    Example 1:
    Class Component with State



    Example 2:
    Functional Component with State using useState Hook


    Example 3:
    Class Component with Form Input and Controlled Component


    Handling Events

    • Handling events in React JS involves using event handlers to respond to user interactions, such as clicks, input changes, or mouse movements.
    • React provides a synthetic event system that wraps native browser events and normalizes them for consistent behavior across different browsers.
    • Understanding and mastering event handling is crucial for building interactive and dynamic user interfaces in React applications.

    Basic Event Handling:

    In JSX, you can specify event handlers by passing functions as props. Event names are written in camelCase, similar to their DOM counterparts.

    Example:

    Passing Arguments to Event Handlers:

    To pass extra data to an event handler, use arrow functions or the bind method to generate a new function.

    Example:

    Preventing Default Behavior:

    We can prevent the default behavior of an event using the preventDefault method available on the event object.

    Example:

    Event Propagation:

    React's event system also supports stopping event propagation using the stopPropagation method.

    Example:

    Using Synthetic Events:

    React provides synthetic events that are similar to native DOM events but with some differences. They are automatically cleaned up when the component is unmounted to avoid memory leaks.

    Example:

    In above example, event is a synthetic event object that wraps the native browser event.

    Conditional Event Handling:

    You can conditionally attach event handlers based on certain conditions.

    Example:

    In above example, event is a synthetic event object that wraps the native browser event.

    Conditional Rendering in React

    • In React, conditional rendering pertains to presenting various components or content depending on specific conditions.
    • conditional rendering enables the dynamic rendering of UI elements based on the application's state or user interactions.

    Conditional Rendering in JSX

    Using the if Statement:

    In JSX, we can use a standard JavaScriptif statement to conditionally render a component or content.

    Example:

    Using the ternary Operator:

    In JSX, we can use a ternary operator to conditionally render a component or content.

    This approach keeps the JSX code cleaner and more readable, especially for smaller conditional blocks.

    Syntax:

    Example:

    Using Logical && Operator:

    We can use the logicalAND (&&) operator to conditionally render elements based on a truthy value.

    This approach is concise and effective, especially when you only need to render a single component based on a condition.

    Example:

    Using Logical || Operator:

    We can use the logicalOR (||) operator to conditionally render elements based on a falsy value.

    This approach is concise and effective, especially when you only need to render a single component based on a condition.

    Example:

    Using Conditional Rendering with Inline Functions:

    This approach allows for more flexibility and enables you to nest conditional rendering within other JSX elements.

    We can use inline functions to conditionally render a component or content based on more complex conditions or logic.

    Example:

    Using Conditional Rendering with switch Statement:

    We can use the switch statement to conditionally render a component or content based on a value.

    For more complex scenarios with multiple conditions, use a switch statement inside the render() method.

    This approach is suitable when you have several different cases to handle, making the code more organized and readable.

    Example:

    Example:

    Explanation:

    We have a state variable isLoggedIn to track the user's authentication status.
    We conditionally render either the WelcomeMessage component if the user is logged in or the LoginForm component if the user is not logged in.
    When the user logs in successfully, the handleLogin function is called to update the isLoggedIn state, triggering a re-render to display the WelcomeMessage component.
    Conditional rendering in React provides a powerful mechanism for building dynamic and interactive user interfaces, allowing you to adapt the UI based on different application states and user interactions.

    Lists and keys in React:

    • In React, lists and keys are essential concepts for rendering dynamic content efficiently.
    • Lists allow you to render a collection of elements.
    • Keys help React identify which items have changed, been added, or been removed.

    Type of Lists and Keys:

    Basic Lists:

    Basic lists render a collection of items without needing to maintain state or handle complex logic.

    Example:

    Dynamic Lists with State:

    Dynamic lists use state to manage the collection of items, allowing for dynamic addition, removal, or modification of list items.

    Example:

    Lists with Unique Keys:

    Unique keys are identifiers assigned to individual items within a list, aiding React in recognizing items during the process of re-rendering

    Example:

    Note:

    • We use the map() function to iterate over each item in the list and render a corresponding JSX element.
    • Each list item have a unique key prop to help React efficiently update the DOM when the list changes.
    • In the case of dynamic lists with state, we use the useState hook to manage the list state and update it as needed.
    • When adding or removing items from a list, React utilizes keys to identify which items have undergone changes, additions, or deletions, thereby optimizing performance and preventing unnecessary re-renders.
    • With applying lists and keys in React, we can efficiently render dynamic content and build interactive user interfaces with ease.

    Forms In React:

    In React, forms are used to collect and process user input. There are several types of forms and various ways to handle form submission and input changes.

    Utilizing different types of forms in React will create powerful and interactive user interfaces for collecting user input and processing data.
    It is better to choose the right type of form that best fits the application's requirements.

    . Uncontrolled Forms:

    Uncontrolled forms allow the DOM to maintain the form data. You can still access form data using a ref, but React does not control the form data.

    Syntax:

    Controlled Forms:

    Controlled forms use React state to control the form data. Each form input element has an associated state value and an event handler to update that state value.

    Syntax:

    Formik Forms

    Formik is a library for building forms in React. It simplifies form management by handling form state, validation, and submission.

    Syntax:

    React Hook Form:

    React Hook Form is another library for building forms in React. It focuses on performance and flexibility by utilizing React hooks.

    Syntax:

    Example:

    Lifecycle Methods in React

    • In React, the component lifecycle refers to the sequence of phases a component goes through from mounting to unmounting.
    • These lifecycle methods provide hooks for executing code at different stages of the component's existence in the DOM.
    • React's class components have lifecycle methods, whereas functional components use hooks to achieve similar outcomes.

    Class Components Lifecycle in React

    A React component's lifecycle encompasses three primary stages:

    Mounting:
    Mounting is the phase in which a component's instance(component) is created and integrated into the DOM.

    This phase includes the following lifecycle methods:

    constructor(props)

    constructor(props) { super(props); // Initialize state this.state = { someState: '' }; // Bind methods this.someMethod = this.someMethod.bind(this); }

    static getDerivedStateFromProps(props, state)

    render()

    componentDidMount()

    Example of Mounting Phase:


    Updating:

    This stage happens when a component undergoes re-rendering as a result of alterations in its props or state.

    Updating phase occurs when a component’s props or state changes, prompting a re-render. The methods involved are:

    static getDerivedStateFromProps(props, state)

    Same as in mounting phase, used for state updates in response to prop changes.

    shouldComponentUpdate(nextProps, nextState)

    render()

    Invoked again to re-render the component.

    getSnapshotBeforeUpdate(prevProps, prevState)

    componentDidUpdate(prevProps, prevState, snapshot)

    Example of Updating Phase:


    Unmounting:

    Unmounting occurs when a component is removed from the DOM.

    There's only one lifecycle method for this phase:

    componentWillUnmount()

    Example of Unmounting Phase:


    React Router

    • React Router is one of the most popular libraries for navigation purpose through pages.
    • It makes the navigation between different components without refreshing the page.
    • React Router create and manage routes in a React application that enables us to develop single-page applications (SPAs).

    Setting Up React Router

    First,create React application using Create React App as below.

    Then Install React Routeras below.

    Example

    Create a some simple components to navigate between.

    For instance, Home.js, About.js, and Contact.js.



    Then create an App.js component to have all the pages to be called in one place

    Note

    • React Router facilitates the rendering of distinct pages or components corresponding to specific URLs, effectively associating each component with a particular path.
    • "/" for Home
    • "/about" for About
    • "/contact" for Contact

    In App.js, the <Routes> component is used as a container for multiple <Route> components.

    Each <Route>defines a mapping between a path and a component.

    When the URL matches the path, React Router renders the specified component.


    . Nested Routes

    • Nested Routes are useful for creating layouts that persist across multiple pages, such as headers, footers, or sidebars.
    • With nested routes, you can have a parent route that renders a common layout component (<Layout>) and child routes that render components within that layout.
    • The <Outlet> component is where the nested routes are rendered.

    Example: A layout with nested routes

    Layout is always rendered, and depending on the URL, Home, About, or Contact is rendered within Layout.

    Nested Routes for layouts

    To create an applications that requires a consistent layout (e.g., shared headers or footers), nested routes allow you to define a common structure that wraps other views.

    Create a Layout component (Layout.js) that includes navigation links and an <Outlet> where child routes are rendered.

    In above we are incorporating the layout into routing by making it a parent route.

    In above approach keeps the navigation consistent across different pages, and enhancing the user experience.

    Example:

    An application with a nested structure: a main layout that contains a navbar, and two main sections, "Dashboard" and "Settings", each with their own sub-pages.

    Layout.js uses an Outlet to render either the "Dashboard" or "Settings" component, while Dashboard.js can further render nested components, such as specific views or widgets, into its own Outlet.


    Dynamic Routes

    Dynamic routes are essential for displaying information that depends on a parameter in the URL, like a specific blog post or product. With React Router.

    Define dynamic segments in the path by prefixing a segment of the path with : (colon).

    For instance, a route for individual blog posts might look like this:


    Protected Routes

    Protected routes are routes that require some form of authentication or authorization.

    To implement it, create a component that checks for user authentication and either renders the requested component or redirects to a login page.

    In below example demonstrates an authentication check.

    If auth.user is not present, it redirects to the /login page.

    Otherwise, it renders the children components, to access to the protected route.

    Example


    Redirecting in React

    Redirects will send users to a different page (The path that originally is not requested).

    For instance redirecting from old URLs to new ones or redirecting unauthenticated users away from protected routes.

    To implement a redirect in React Router,
    use the <Navigate> component with the replace prop to prevent the original route from being added to the history stack:

    Syntax

    In above syntax, it automatically redirect anyone who navigates to /old-path to /new-path instead.

    Note

    The Outlet and layout components in React Router are crucial for creating complex applications with nested routes

    The developer can build a consistent build a consistent structure across various pages.

    Outlet is a component provided by React Router that serves as a placeholder for rendering child routes.

    It is used within parent route components to specify where child routes should be rendered.

    This mechanism is particularly useful for creating nested routes.

    Example

    In your main application file (App.js)
    we define routes using Layout as a wrapper for other content.

    Example

    Note :Layout Components

    A layout component in React Router defines a structure that should be present across multiple routes.(A layout component in React Router is used to define a common structure (include headers, footers, sidebars, or any other persistent UI elements) that should be present across multiple routes.

    The layout component typically wraps the Outlet component till nested routes are rendered within the context of this structure.

    Hooks

    • In React, hooks refer to functions that enable the utilization of state and other React functionalities within functional components.
    • They provide a way to reuse stateful logic without changing the component hierarchy.

    Below are the primary categories of Hooks in React.

    State Hooks:

    Syntax:

    Example:

    Effect Hooks:

    • useEffect(): Allows performing side effects in functional components, such as data fetching, subscriptions, or manually changing the DOM.

    Syntax:

    Example:

    Context Hooks:

    • useContext(): Allows passing data between components.
    • It Allows functional components to consume values from a context without wrapping the components in consumers.

    Syntax:

    Example 1:

    Example 2:

    Ref Hooks:

    • useRef(): Allows functional components to hold a mutable reference to a DOM node or a value.

    Syntax:

    Example:

    Reducer Hook:

    • useReducer(): An alternative to useState(), useful for managing more complex state logic(When state objects contain multiple sub-values).
    • Use it when the next state depends on the previous one.

    Syntax:

    Example:

    useCallback Hook

    • useCallback(): A React hook that returns a function that, when called, invokes the original function.
    • It provides a cached variant of the callback function.
    • It updates only when any of its dependencies change.
    • It is beneficial when passing callbacks to optimized child components that depend on reference equality to avoid redundant renders.

    Syntax:

    Example:

    useMemo Hook

    • Much like useCallback, useMemo recalculates the memoized value solely when any of its dependencies alter.
    • It is good for computationally intensive tasks.

    Syntax:

    Example:

    Custom Hooks:

    • With custom Hooks you can create your reusable logic with hooks.
    • It is good for when you want to use any of the aforementioned hooks and return anything you want.

    Example:

    React Fragments

    React Fragments enables the bundling of multiple child elements without the need for additional nodes in the DOM.

    For this purpose use <React.Fragment> or its shorthand syntax <> ... </>

    Syntax 1:



    Syntax 2

    In above example, MyComponent returns two <div> elements wrapped in a React.Fragment.

    The grouping does not add an extra layer to the DOM.

    It keeps the structure clean and efficient.

    Fragments can accept keys, which is useful when mapping a collection to an array of elements, making them quite handy.

    Context API in React

    • The Context API in React is a way for components to effectively produce and use data at different levels of the component tree without needing to explicitly pass props down through every level.
    • It is useful for sharing data that is 'global' for a tree of React components, such as authenticated user information, theme settings, or language preferences.
    • Without Context API we have to pass data through the component tree by passing props down manually at each level, which could be cumbersome and inefficient for certain types of global data.
    • The Context API makes the code cleaner and more maintainable.

    How to use Context API

    • 1-Create a Context:
      Creating context is done by using React.createContext(), which returns a Context object.
      The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.
    • 2-Provide a Context Value: Use a Provider component that comes from the created Context object to wrap the part of your component tree that needs access to the context data. Any component within this tree can access the context value.
    • 3-Use or consume the Context Value:
      Components use the data can access it in two primary ways:
      A) Context.Consumer Component: This is a React component that subscribes to context changes.
      It requires a function as a child, which receives the current context value and returns a React node.
    • Syntax:

      B) useContext Hook:

      This is a simpler and modern way to consume or use context
      It is available in functional components.
      It takes the context object itself as an argument and returns the current context value.

      Syntax:

    The Context API in React is a tool for:
    handling global state
    and transmitting data across the component hierarchy.
    Nevertheless, it doesn't used for all scenarios of state management.

    1. Component Boundaries:
    2. Functional or component separation or decomposition: Break down the UI into smaller, reusable components(function) that each have a single responsibility.
      This promotes code reuse and makes components easier to understand and maintain.
      This is the most common type of boundary.

      Container Components vs. Presentational Components:

      Container components are responsible for data fetching and state management.
      Presentational components do focus on rendering UI.
      This maintains a clear separation of data and presentation logic.



    3. State boundaries:
    4. Local Component State:
      Use local state within components for managing UI-specific state that doesn't need to be shared with other components.

      Use global State Management with the use of state management libraries like Redux, Context API, or Recoil for managing global application state that can be accessed across multiple components.
      This centralizes state logic and avoid using prop.


    5. Code Splitting boundaries
    6. Dynamic Imports: Employ dynamic import() to partition your code into smaller units that are fetched as needed.
      This approach enhances the initial page loading speed by only loading the code essential for the present view.

      React.lazy() and Suspense:
      React.lazy() and Suspense are two features in React used to do code splitting and improving the performance of your application by loading components asynchronously .

      React.lazy():

      React.lazy() is a function that dynamically import a React component(loads only components that are needed to load th app).
      It significantly improve the initial loading time of the application(especially for large applications that has lots of components).

      Syntax:

      Think we have a component named MyComponent that you want to import lazily:

      Example:

      Import it lazily in another component as follows:


      Suspense:

      Suspense is a React component that specify loading indicators while waiting for some asynchronous code to resolve(like lazy loading of components).
      It is managing the loading state of the application and displaying a fallback UI until the required data or components are loaded.

      Syntax:

      Note:

      In the example above, we see Suspense wraps the lazy-loaded component <LazyLoadedComponent >.
      The fallback prop specifies what should be rendered while the component is loading. /p>

      Example:

      Note:

      While the LazyLoadedComponent is being fetched and loaded asynchronously, We see a loading indicator instead of a blank screen, providing a better user experience.


    7. ErrorBoundary Component
    8. Error Boundaries: Use error boundaries to handle errors (catch JavaScript errors) that occur in your application.
      It prevents the application from crashing when an unexpected error occurs.

      Error boundaries in React catch JavaScript errors occurring in their child component tree.

      Instead of letting these errors disrupt the user experience, error boundaries log them and display a backup UI.


      It is essential to use them for maintaining a smooth interface despite errors.

      These boundaries capture errors during rendering, lifecycle methods, and constructors of all components below them.



    9. Context Boundaries:
    10. Context Providers:
      Use Context API to pass data or functions down through the component tree without manually passing props at each level. Use or define context providers at appropriate boundaries to encapsulate related state or behavior.


    11. Server-Side Boundaries:
    12. API Endpoints:
      Create or define clear boundaries between client-side and server-side logic.

      Use API endpoints to communicate between the frontend and backend parts of your application, ensuring separation of concerns and security.


      Establishing boundaries in React application make the codes cleaner, more maintainable and a better development experience.
      It facilitates collaboration among team members and promotes code reuse and scalability.

    1. Higher-Order Components (HOCs)is an extension of existing components' functionality.
    2. HOCs function as wrappers accept a component as input and yield a new component with supplementary props or behavior.
    3. HOC is an advanced technique in React for reusing component logic.
    4. They are functions that take a component and return a new component(They enhance the original component with additional properties or functionality.
    5. We use HOC when we want ot share same functionality for many components
    6. It makes the code cleaner and maintainable(not use repeated code for many Components).
    7. We can a HOC to modify or add new props to a component before it is rendered.
    8. Wrap the component at the export stage or in the export statement.
    9. HOC modifies props before passing them to a component.
    10. HOC manages state or access lifecycle methods in a reusable way.
    11. HOC conditionally renders components based on certain criteria like user permissions.

    Syntax:

    Example 1:

    Example 2: Data Fetching

    Example 3: Loading Spinner

    Example 4: Error Handling

    Example 5: Authentication

    Example 6: Styling

    HOC will wrap the component at the export stage or in the export statement.

    Or

    Example 7: HOC called withLogging that logs props to the console before rendering the wrapped component

    Explanation:

    We define the withLogging HOC, which takes a WrappedComponent as an argument.

    Inside the HOC, we return a new component that renders the WrappedComponent and logs its props before rendering.

    We then wrap our MyComponent with the withLogging HOC to create the EnhancedComponent.

    When EnhancedComponent is rendered, it logs the props before rendering MyComponent.


    Example 6: Adding a greeting to multiple components based on the user's status

    Use the above (example 6) to enhance any component

    Note:
    HOC should pass through props to the wrapped component.


    HOC will wrap the component at the export stage or in the export statement.
    HOC is a function that takes a component as its input.
    We use HOC to avoid code repetition. For example you want to add checks to so many components individually, you can create an HOC that does this check and use it to wrap all these components.
    When you want to separate components (functions) such as fetching data, handling authentication use HOC.

    Common Use Cases for HOCs:

    1. Code Reuse: HOCs allow you to encapsulate common functionality (e.g., logging, authentication, data fetching) and apply it to multiple components.
    2. Prop Manipulation: HOCs can add, remove, or modify props passed to the wrapped component based on certain conditions or requirements.
    3. State Management: HOCs can inject state into components or manage stateful logic (e.g., form handling, state synchronization).
    4. Conditional Rendering: HOCs can conditionally render components based on certain conditions or user authentication status.
    5. Performance Optimization: HOCs can optimize component rendering by memoizing components, implementing shouldComponentUpdate logic, or lazily loading components.

    Note:

    HOCs introduce an additional layer of component abstraction, which can sometimes make the component hierarchy more challenging to understand.

    HOCs do not modify the original component. Instead, they create a new component with enhanced functionality, which may affect component identity and lifecycle methods.

    HOCs are a powerful tool, but overuse can lead to code complexity and reduced readability. Use them judiciously and consider alternative patterns such as Render Props or Hooks when appropriate.

    Overall, Higher-Order Components are a valuable tool in the React developer's toolkit for enhancing component functionality, promoting code reuse, and improving application architecture.

    HOCs are like kind of wrappers for the components to add additional functionalities (like checking for login, handling errors, loading data) without making changes to the original components. It is helpful in reusing code and keeping components organized.

    Testing in React

    Jest

    It is maintained by Facebook, stands as a JavaScript testing framework, easy to use with rapidity, and robust capabilities. It offers features like snapshot testing and mocking.

    Syntax for Running Tests:

    Example Test File:


    React Testing Library:

    React Testing Library, a testing utility designed for React.
    It mirrors user interaction with the application.
    It provides a user-friendly and simple API for querying and interacting with components.

    React Testing Library is a powerful tool for testing React components.

    It tests that components behave correctly.

    React Testing Library integrates with popular testing frameworks like Jest.
    We can write and run tests within our existing testing setup.

    Example 1: Test File

    Example 2

    Key Testing Features

    1. Rendering Components: Use render methods provided by testing libraries to render React components in a test environment.
    2. Querying Elements in the DOM: Use query methods (e.g., getByText, getByTestId) to query and interact with rendered elements in your tests.
    3. Prediction: Use assertion or prediction functions (e.g., expect) to make assertions about the expected behavior or appearance of components.
    4. Mocking Dependencies: Use mocking techniques to replace dependencies (e.g., API calls, external libraries) with mock implementations for isolated testing.
    5. Snapshot Testing: Use snapshot testing to capture the rendered output of components and detect unexpected changes in subsequent test runs.

    Integration Testing:

    For integration testing, we use tools like Cypress or testing library's testing frameworks.

    Example with Cypress

    Tips in testing:

    1. Simplified concise targeted tests that analyze individual aspects of component's functionality.
    2. Validate and verify user interactions and guarantee the desired behavior of the components.
    3. It tests responsiveness that covers different screen sizes and browser environments to confirm compatibility across platforms.
    4. Implement Continuous Integration: Embed testing within your continuous integration (CI) workflow to automate testing and detect issues early during development.
    5. Adhering to best practices and utilizing suitable testing frameworks.
      It enhances the reliability and resilience of your React applications.
      It explores a range of testing methods and libraries to determine the most suitable approach for the project.

    Styling in React

    In React, there are several ways to style components. Here are some common methods to style the React App.

    Inline Styles:

    W can apply styles directly within the JSX using JavaScript objects.


    CSS Stylesheets:

    We can create separate CSS files and import them into your components.



    Styled Components:

    Styled Components offer a way to write CSS directly within your JavaScript files.

    CSS-in-JS Libraries (other than Styled Components):

    There are other libraries similar to Styled Components that allow you to use CSS-in-JS, such as Emotion.

    These libraries let you write CSS directly in your JavaScript, providing dynamic styling capabilities.


    Tailwind CSS:

    A utility-first CSS framework that can be used in React for rapidly building custom designs by composing utility classes.


    SASS/SCSS:

    SASS/SCSS is a scripting language that pre-processes code before it's converted into CSS. It offers enhanced capabilities compared to standard CSS, including features like variables, nested rules, mixins, and additional functionalities


    Inline CSS with React's style Attribute (Dynamic Styling):

    We can dynamically change styles based on props or state.

    Example: Dynamic Inline Style



    Each of these methods has its own set of advantages.
    Inline styles and CSS-in-JS libraries like Styled Components or Emotion are great for components that require dynamic styles based on props or state.
    CSS, SASS/SCSS, and CSS Modules are excellent for more static, global styles.
    Tailwind CSS is favored for its utility-first approach and rapid prototyping capabilities.
    The choice often depends on the project requirements, scalability needs, and developer preference.

    Fetching Data in React

    The Fetch API comes integrated into contemporary browsers, offering a straightforward and robust mechanism for asynchronously retrieving resources or data.

    Syntax:

    Example:


    Axios

    A popular HTTP client library to make AJAX requests in JavaScript.

    Syntax

    Example


    useEffect Hook with Fetch API:

    Use of the useEffect hook in combination with the Fetch API for data fetching.

    Example:

    Three common approaches to fetching data in React:
    using the Fetch API
    using Axios library,
    using the useEffect hook.

    Each method has its advantages.
    Choose the one that best fits the project requirements and preferences.
    Additionally, handle loading and error states appropriately to provide a better user experience.

    What is Redux?

    • Redux is a dependable state container for JavaScript applications,
      It is adaptable to various frameworks.
    • It is to facilitate the management of the application's global state (within a unified store).
      It ensures predictability in state alterations(through the use of actions and reducers).

    The fundamental principles in Redux include:

    • All state information for the entire application resides in a store (a single object tree).
    • Changes to the state can only occur by dispatching actions (Immutable State).
    • State transformations in response to actions are done by reducers (ensure predictability and reliability).

    Key Components:

    • Actions:
      These are JavaScript objects that define events within the application. Actions must possess a type property specifying the action's nature.
    • Reducers:
      These are pure functions, taking the current state and an action (as inputs), and producing the subsequent state of the application (as output).
    • Store:
      It is a repository for the application's state,
      Store provides mechanisms for accessing the state, dispatching actions, and managing listeners' registration and removal.

    Syntax:

    Action with example


    Reducer with example

    Reducers (function) specify how the application's state changes in response to actions sent to the store.

    Store with example:


    Example:

    Todo App

    Demonstrating in a todo application context in a place:
    create actions, reducers, and a store .


    Note:

    Action versus Reducer:

    Actions

    • It is the only method for introducing data into the store
    • Each action is required to have a type property (a string that identifies the type of action being executed). Actions may include additional data in properties other than type.
    • Actions tell us what occurred, not the changes that occur in the application’s state.
    • They are sent to the Redux store
    • Actions communicate data to the store.
    • Actions initiate changes in state.
    • Actions, are static and carry information.
    • Within a Redux framework, actions tell us something has occurred, prompting reducers to adjust the state in response to these announcements

    Reducers

    • A reducer is a function that display how the state of the application changes in response to actions dispatched to the store.
    • It ensures that state transitions are implemented correctly and uniformly.
    • Reducers accept two parameters: the current state and an action.
    • They produce the new state and must be pure functions—that is, they should consistently return the same output for the same inputs and not have side effects.
    • Reducers define the changes in the application's state following the actions it receives. This function is where the logic for state updates is formulated.
    • Reducers process this data to update the state based on the logic defined within them.
    • Reducers establish how these changes occur.
    • Reducers create a new state from the existing one without altering it directly.

    Integrating Redux with React

    How to use Redux with React:

    • Use the react-redux library, which provides a component to pass the Redux store to your React application.
    • Use a connect() function to connect your React components to the Redux store.

    A Basic react-redux Setup

    Redux provides a robust solution for managing global state in complex applications.

    It makes state mutations predictable and easier to manage.

    React Patterns

    In React, patterns are commonly used approaches or strategies for structuring code, managing state, handling data flow, and improving code organization and reusability.

    Some common patterns in React:

    1. Container-Component Pattern:
    2. Also known as the "Smart-Dumb Component" pattern, this pattern separates components into two categories: container components and presentational components. Container components are responsible for data fetching, state management, and business logic. Presentational components are concerned only with UI rendering and receive data via props.

      Syntax

      Explanation:

      Container components handle data fetching and state management using hooks like useState and useEffect.

      Presentational components receive data via props and are focused solely on rendering UI based on the provided data.


    3. Render Props Pattern:
    4. The Render Props pattern involves passing a function as a prop to a component, allowing the component to render content using the function's return value.

      It promotes code reuse by enabling components to share behavior and logic through a common interface.

      Syntax:

      Explanation:

      The MyComponentWithRenderProp component receives a render prop, which is a function that returns the content to be rendered.

      By passing different functions to the render prop, you can control what content is rendered by the component, allowing for flexible and reusable components.


    5. Higher-Order Component (HOC) Pattern:
    6. Higher-Order Components are functions that accept a component as input and return a new component with enhanced functionality.

      They enable code reuse and cross-cutting concerns such as logging, authentication, or data fetching.

      Syntax:

      Explanation:

      The withHOC function takes a component as input and returns a new component that enhances the functionality of the input component.

      The enhanced component can include additional props, state, or behavior provided by the HOC.

      Applying patterns can improve code organization, reusability, and maintainability in your React applications.

    React Performance Optimization

    React performance optimization is crucial for ensuring smooth and efficient rendering of your applications, especially as they grow in complexity.

    Techniques that optimize React applications:

    1. Memoization:
    2. Memoization involves caching the outcomes of costly function invocations and retrieving them when identical inputs reappear.

      In React, you have the option to employ either the React.memo Higher-Order Component or the useMemo hook for memoizing components or values, respectively.

      useMemo

      useMemo is a React hook that returns a memoized version of a function.

      It reduces unnecessary re-renders of components or recomputation of values.

      It improves rendering performance by avoiding redundant work.


    3. Virtualization:
    4. Virtualization is a technique for rendering large lists or grids efficiently by only rendering the items that are currently visible on the screen.

      Libraries like React Virtualized or React Window provide components for virtualizing lists and grids.

      It improves performance and reduces memory consumption when rendering large datasets

      It enables smooth scrolling and interaction with large lists or grids.

      Example: React Virtualized


    5. Code Splitting:
    6. Code splitting involves breaking down your application into smaller bundles or chunks that are loaded asynchronously.

      React.lazy and Suspense enable you to load components lazily, improving initial loading time and reducing the size of the main bundle.

      It reduces initial load time by loading only the necessary code for the current view.

      It improves perceived performance by displaying loading indicators during component loading.

      Syntax (React.lazy and Suspense):


    7. PureComponent and shouldComponentUpdate:
    8. PureComponent and shouldComponentUpdate are strategies aimed at enhancing rendering performance by avoiding unnecessary re-renders of components.

      PureComponent conducts a shallow examination of props and state to ascertain if a component necessitates an update.

      shouldComponentUpdate affords the flexibility to tailor the criteria dictating when a component should undergo an update.

      It reduces unnecessary re-renders of components, improving rendering performance.

      It enhances overall application performance by minimizing unnecessary work in the render cycle.

      Syntax (PureComponent):

      Syntax (shouldComponentUpdate):


    9. . Use Performance Tools:
    10. React provides various performance tools for measuring and optimizing the performance of your applications.

      Tools like React DevTools, Chrome DevTools, and performance monitoring libraries help identify performance bottlenecks and optimize rendering performance.

      Use React DevTools to inspect component hierarchies, measure component render times, and identify wasted renders.

      Provides insights into component performance and rendering bottlenecks.

      Enables targeted optimizations to improve overall application performance.

      These techniques and tools, you can optimize the performance of your React applications, ensuring smooth rendering and improved user experience, even as your application grows in complexity.

      Remember to measure performance regularly and prioritize optimizations based on profiling data and user feedback.

    Server-Side Rendering (SSR):

    1. Server-side rendering (SSR) involves the procedure of generating web pages on the server and transmitting the fully rendered HTML to the client.
    2. This method enables search engines and social media crawlers to view a fully rendered page, thereby potentially enhancing SEO and initial page load performance.
    3. It enhances SEO (Complete pages can be crawled and indexed by search engines, resulting in improved search engine rankings).
    4. It Accelerates initial page load (Users receive a fully rendered page directly from the server, reducing the time required for rendering within the browser).
    5. It enhances performance on low-powered devices(SSR has the potential to boost performance on low-powered devices by shifting rendering tasks to the server).
    6. One challenge it is facing is increased Server Load(SSR can increase server load since the server needs to render pages for each request).
    7. Other challenge it is facing is Complex Setup (Implementing SSR requires additional configuration and infrastructure compared to client-side rendering).

    What is Next.js?

    1. Next.js stands as a widely-used React framework, offering integrated assistance for server-side rendering, static site generation, and other advanced functionalities.
    2. It streamlines the development of React applications by incorporating server-side rendering capabilities.
    3. Next.js(Server-Side Rendering (SSR)) features inherent support for SSR, enabling the rendering of React components on the server and transmission of HTML to the client.
    4. Next.js ( File-based Routing)employs file-based routing, associating each page with a corresponding file in the pages directory.
    5. Next.js( API Routes) permits the definition of API routes within the pages/api directory, facilitating the development of backend APIs alongside frontend code.
    6. Next.js (Automatic Code Splitting) automatically divides code into smaller segments, diminishing the initial load duration of your application.
    7. Next.js (Built-in CSS and Sass Support) integrates built-in support for CSS and Sass, enabling the direct importation of stylesheets into your components.
    8. Next.js is widely used for building React applications that require server-side rendering, static site generation, or other advanced features.
    9. It's particularly popular for building e-commerce websites, blogs, and content-heavy applications where SEO and performance are critical.
    10. By leveraging Next.js, developers can build powerful React applications with enhanced performance, SEO, and developer experience out of the box.
    11. It abstracts away much of the complexity involved in setting up server-side rendering and provides a streamlined development
    12. Next.js (as Static Site Generation (SSG)) facilitates static site generation, wherein pages are pre-rendered during build time, resulting in accelerated page loads and enhanced SEO.

    Syntax: bash

    Example

    GraphQL

    1. GraphQL is a query language for APIs and a runtime for executing those queries with your existing data.
    2. GraphQL is commonly used to fetch and manage data from a server efficiently in React.
    3. In a single request get or fetch exactly the data, you asked for your component in GraphQL and reduce over-fetching and under-fetching of data(Efficient Data Fetching).
    4. GraphQLis good for building efficient and scalable web applications, particularly in data fetching and management that are complex or dynamic.
    5. GraphQL API is defined by a schema, providing clear and predictable data structures, which can be beneficial for frontend developers working with complex data models(Strongly Typed Schema).
    6. GraphQL queries are declarative (not telling you the step by step procedures to get the output - tell you as a whole how the UI will be), making it easier to express data requirements.
    7. GraphQL APIs provide a single endpoint (Centralized Data Management) for data fetching and updating which simplifies data management.
    8. It enables developers to fetch and manage data declaratively, efficiently, and with strong typing, improving both development speed and application performance.

    When to use GraphQL in React?

    1. When your React application needs to fetch data from multiple endpoints or various sources(Complex Data), GraphQL can simplify data fetching by providing a single endpoint for all data requirements .
    2. For large-scale React applications with complex data models and numerous data requirements, GraphQL can improve performance, scalability, and maintainability by reducing over-fetching and under-fetching of data(in a large-scale applications).
    3. If your application requires real-time data updates or subscriptions, GraphQL can efficiently handle real-time data streaming and push updates to connected clients(Real-time Data Updates).
    4. When frontend and backend teams work collaboratively on a project, GraphQL's strongly typed schema and introspection capabilities (ability to examine and understand the structure, behavior, and state of React components during runtime) can facilitate communication and alignment between frontend and backend developers(Collaborative Development).

    Syntax:GraphQL Query

    Syntax: GraphQL Mutation(modify data on the server includes creating deleting and updating data. )

    Example: A simple React application using GraphQL to fetch and display user data

    React Animation Libraries

    1. React animation libraries create interactive user interfaces with animations.
    2. These libraries animate components on enter, exit, mount, unmount, and during state changes.

    What are some popular React animation libraries?

    1. Framer Motion
    2. Offers advanced features like shared element transitions for layout animations, motion values for coordinating and managing multiple animations across components.
    3. Simple and powerful syntax for creating animations.
    4. Supports gesture animations (like drag and swipe).
    5. If you want to implement simple animations quickly, Framer Motion offers a simple and intuitive API.

    Example:


    React Spring

    1. Spring-physics based animation library, great for natural and fluid motion.
    2. Supports animating styles, SVG properties, and more.
    3. Works well with a wide range of UI elements and use cases, from simple animations to complex interactive UIs.
    4. React Spring are optimized for performance, even for complex animations.

    Example:

    React Motion

    1. Ir provides a simple declarative syntax for defining animations.
    2. Utilizes spring configurations for creating physics-based animations().
    3. Focuses on robust and natural motion transitions.
    4. If your project requires complex and unique animations, you might prefer a library that offers more control and customization, like React Spring or React Motion.

    Example:

    React Transition Group

    1. Offers a way to perform animations when a React component enters or leaves the DOM.
    2. Provides components like Transition, CSSTransition, and SwitchTransition for managing complex animations.
    3. Great for animating lists, dialogs, and conditional rendered components.

    Example:

    What is D3.js?

    1. D3.js (Data-Driven Documents) is a JavaScript library for producing dynamic, interactive data visualizations in web browsers.
    2. It utilizes the full capabilities of modern browsers (like SVG, Canvas, and HTML) to create rich graphical representations of data.
    3. D3 is highly flexible, allowing you to bind arbitrary data to a Document Object Model (DOM), and then apply data-driven transformations to the document.
    4. D3 allows you to bind data to the DOM, creating a rich, interactive, and dynamic visual representation of that data(Data Binding).
    5. It uses web standards like HTML, SVG, and CSS to render visuals, which means you can create complex charts and graphs that are scalable and customizable(DOM Manipulations).
    6. D3 provides powerful transition capabilities, enabling you to animate changes to the data or the visualization(Transitions).
    7. It supports user interaction with the visual elements, allowing for interactive data visualizations that can respond to mouse events, touch events, and more(Interactivity and Events).
    8. D3's functionality is divided into modules. You can use individual components as needed, which keeps your projects and code lightweight(Modularity).
    9. D3 syntax is method-chained, which means you select an element, apply changes or bind data, and then apply further changes or transitions.
    10. When your project requires complex, interactive, or real-time data visualizations, D3.js shines by offering full control over the final visual output(complex data visualization).
    11. If you need custom charts or visualizations that go beyond standard charting libraries, D3.js provides the tools and flexibility to build these from scratch(custom visualization).
    12. Understanding D3.js can deepen your knowledge of how data can be manipulated and visualized in the browser, teaching you the fundamentals of SVG, transitions, scales, and data binding.

    Example: create a bar chart:javascript

    HTML file

    JavaScript (chart.js):

    What is PWA?

    1. Progressive Web Apps (PWAs) are web applications that use modern web capabilities to provide a user experience similar to that of mobile apps.
    2. When building PWAs with React, you leverage React's component-based architecture along with service workers, web app manifests, and other modern web features to create fast, engaging, and reliable applications accessible through browsers.
    3. PWAs work on any device and fit any screen size(Responsiveness).
    4. They can work offline or on low-quality networks, thanks to service workers(Connectivity Independence).
    5. PWAs feel like native apps with smooth interactions and navigation(App-like Interaction).
    6. Always up-to-date due to the service worker update process(fresh).
    7. Served via HTTPS to prevent snooping and ensure content hasn't been tampered with(Safe).
    8. Identifiable as applications thanks to W3C manifests and service worker registration, allowing search engines to find them(Discoverable).
    9. Make re-engagement easy through features like push notifications(Re-engageable).
    10. Allow users to "keep" apps they find most useful on their home screen without the hassle of an app store(Installable).
    11. Easily shared via a URL and do not require complex installation(Linkable).

    To create a PWA with React, you can start with Create React App (CRA), which includes a service worker and a web app manifest by default, providing a good starting point for developing PWAs.

    Step 1: Set Up React App

    Step 2: Make Your React App a PWA

    Service Worker: The default service worker in CRA only works in production build. You can customize it for more advanced offline capabilities. Ensure the service worker is registered in your index.js:

    Web App Manifest: Customize the public/manifest.json file with details about your app. This file defines how your app appears on the user's home screen and how it can be launched.

    HTTPS is essential for PWAs to guarantee a secure connection. During development, the Create React App development server automatically utilizes HTTPS. When deploying to production, make sure your hosting provider offers support for HTTPS.

    Add Offline Capabilities: This is where the power of service workers comes in. You can customize the service worker script to cache the application shell (HTML, CSS, JavaScript files) and app data for offline use.

    Deploy Your App: When you're ready, build your app for production

    Deploy your app to a secure web server that supports HTTPS. Many hosting platforms like Netlify, Vercel, and GitHub Pages offer simple, secure hosting for PWAs.

    Testing Your PWA

    Lighthouse: Use Google's Lighthouse tool to audit your PWA. It provides insights into performance, accessibility, progressive web app metrics, SEO, and more.

    Manual Testing: Test your PWA on various devices and browsers to ensure it meets your expectations in terms of performance, responsiveness, and functionality.

    PWAs with React combine the best of web and mobile app features. With service workers for offline work and background syncing, a manifest file for add-to-home-screen and full-screen capabilities, and push notifications for user re-engagement, PWAs can provide a user experience comparable to native apps while remaining lightweight and accessible through a browser.

    What are Micro Frontends in React?

    1. Micro Frontends are a way of organizing and broken down a website into small, semi-independent parts called 'microapps' that work together loosely.
    2. This means splitting a big website into smaller pieces that can be worked on, launched, and looked after separately.
    3. This setup allows different teams to handle different parts of the website using different tools or versions.
    4. Each micro frontend can operate independently of others(Decoupling).
    5. Teams can choose their technology stack and release cycle(Autonomy).
    6. Shared components can be used across different micro frontends(Reusable Components).
    7. Ensures consistent look and feel and user experience across the application, despite being built by different teams(Consistency).
    8. In React, micro frontends are like building blocks for big apps.
    9. They make it easier to handle large projects by splitting them into smaller parts.
    10. This makes development faster, helps the app grow smoothly, and lets different teams focus on their own tasks.
    11. But, it's crucial to think about how all these parts fit together and how it might affect how fast the app works.
    12. If done right, micro frontends can be a big help for big projects.

    Implementation:

    The choice of strategy depends on factors like your project's requirements, the size of your team, and how independently you want to deploy each part of your application.

    1. Build-Time Integration:
    2. In this approach, micro frontends are integrated during the build process. Webpack Module Federation is a popular choice for this, allowing a JavaScript application to dynamically load code from another application.

      Example:

      webpack.config.js in App 1:

      webpack.config.js in App 2:


    3. Run-Time Integration via iFrame or Web Components:
    4. Run-time integration involves loading micro frontends at runtime. iFrames and Web Components can encapsulate micro frontends, ensuring independence in terms of styling and JavaScript execution.

      Example with web components:

      index.html in the main app

      In micro frontend:


    5. Run-Time Integration via JavaScript:
    6. This method involves dynamically loading micro frontends as JavaScript applications at runtime. This could be done through script tags, SystemJS, or import maps.

      Example with dynamic script loading:

    Note:

    Styling Isolation: Avoiding CSS leaks and ensuring consistent styling across different micro frontends.

    State Management: Managing application state across micro frontends can be challenging.

    Performance: Extra care must be taken to manage the size of the application and loading times, especially with run-time integration.

    Routing: Coordinating routing between micro frontends to provide a seamless user experience.

    What is React Native?

    React Native is an open-source framework for building native apps for iOS, Android, and the web. React Native is built on top of JavaScript, and runs on top of the React JavaScript library.

    React Native is a tool made by Facebook using JavaScript. Even though it's related to React.js, it's a bit different.

    React Native is a great tool for making apps that work on different types of phones using React's building blocks.

    It's important for developers to know these differences if they want to build websites or mobile apps with React.

    Even though React.js and React Native have similar ideas and ways of writing code, they're meant for different things and work in different ways.

    React Native vs. React.js:

    Platform Targeting:

    >React.js (React): Targets web browsers and web applications.

    React Native: Targets native mobile platforms like iOS and Android.

    UI Components:

    React.js: Uses HTML, CSS, and virtual DOM for rendering UI components in web browsers.

    React Native: Uses native UI components provided by the respective mobile platforms (UIKit for iOS, Android SDK for Android).


    Development Environment:

    React.js: Developed and tested in web browsers.

    React Native: Developed using React Native CLI or Expo CLI and tested on simulators/emulators or real devices.


    Styling:

    React.js: Uses CSS for styling web components.

    React Native: Uses StyleSheet API for styling components with JavaScript, which gets converted into native styles.


    API Access:

    React.js: Accesses browser APIs like DOM, localStorage, etc.

    React Native: Accesses native device APIs like Camera, Geolocation, etc., using JavaScript interfaces provided by React Native.


    Development Tools:

    React.js: Developers use browser-based developer tools like React DevTools for debugging and inspecting components.

    React Native: Developers use platform-specific debugging tools like Xcode for iOS and Android Studio for Android.


    Syntax:

    The syntax in React Native is similar to React.js, with some platform-specific components and APIs for mobile development. Here's a simple example of a React Native component:

    While React.js and React Native share some common concepts, there are also topics specific to each:

    React.js Topics:

    1. Virtual DOM
    2. JSX syntax
    3. Components and Props
    4. State and Lifecycle
    5. Hooks (useState, useEffect, etc.)
    6. Context API
    7. Forms and handling user input
    8. Router (React Router)
    9. Redux and state management
    10. Testing (Jest, React Testing Library)

    React Native Topics:

    1. Native components (View, Text, Image, etc.)
    2. StyleSheet API for styling
    3. Navigation (React Navigation)
    4. Device APIs (Camera, Geolocation, etc.)
    5. Handling platform-specific code
    6. Performance optimization for mobile devices
    7. Debugging on mobile simulators/emulators and real devices
    8. Publishing and distribution of mobile apps

    Contributing to React open source means getting involved in making React and its related projects better.

    Here's how you can help out how you can contribute to React open source:

    1. Find Where to Help:

      1. Core React libraries: Fix bugs, add new features, make it faster, or improve the documentation.
      2. React Ecosystem: Work on projects like React Router, Redux, React Native, or Next.js.
      3. Documentation: Make the official docs clearer and fix any mistakes.
      4. Community Projects: Help out with projects made by the React community.
    2. Understand How to Help with Contribution Guidelines:

      1. Read the guidelines: Learn about how to contribute, what rules to follow, and what's planned.
      2. Setup Development Environment: Set up a development environment for contributing to React by following the instructions provided in the repository's README file.
      3. Learn Git: Understand how to use Git and GitHub to manage and share your work(for version control and collaboration).
    3. Pick What to Work On:

      1. Fix Bugs: Find and solve problems that people have reported(reported in the issue tracker).
      2. Add Features: Make new things or improve existing ones based on requests(Implement new features or enhancements).
      3. Speed Up: Make React work faster by improving the way it does things(Better performance:by improving algorithms, reducing overhead, or optimizing code).
      4. Help with Docs(Enhance Documentation): Make the documentation better by adding examples or making it easier to understand.
      5. Review Code: Check other people's work and give feedback.
      6. Test: Make sure everything works by writing and improving tests.
    4. Send Your Changes(Contribute Code):

      1. Copy the Project(Fork the Repository): Make your own copy of React on GitHub.
      2. Make a Branch: Create a new branch for your changes(preferably named after the feature or bug you're working on).
      3. Make Changes(Commit Changes): Write your code, explain what you did, and put it in your copy(commit them with descriptive commit messages, and push them to your forked repository).
      4. Ask for Review(Submit a Pull Request): Tell the main React team (the main React repository) about your changes by making a pull request (detailing the changes you've made and addressing any related issues.).
    5. Be Part of the Community:

      1. Talk with Others: Join conversations about React on GitHub or in forums.
      2. Join Events: Go to meetups or online events to meet other React developers.
      3. Help Others: Answer questions and give advice to other people who are contributing.
    6. Keep Things Good(Maintain Code Quality):

      1. Follow Rules(coding Standards): Adhere to the coding standards, style guides, and best practices( maintain code consistency and readability).
      2. Test Your Code: Make sure everything works before you send it(Write unit tests, integration tests, and end-to-end tests to ensure code reliability).
      3. Stay Informed: Know what's happening with React and the people working on it(Keep up-to-date with the latest changes, updates, and announcements).
    7. Get Noticed(Receive Recognition):

      1. Get Credit: Your work will be mentioned in the project's notes and documentation.
      2. Build Your Resume or portfolio: Contributing to React looks great on your resume or portfolio and shows you're skilled.
      3. Meet People: Working on React means meeting lots of other developers and learning from them.

    By helping with React, you can make it even better, connect with other developers, and be part of a big community.