Namaste React Series - Part 1 (Basics)

ยท

6 min read

React has revolutionized the way we build user interfaces, becoming a cornerstone in modern web development. Its declarative and component-based approach empowers developers to create dynamic, interactive, and scalable applications with ease. In this blog, we'll delve into the core concepts, best practices, and the power of React, unlocking its potential to craft immersive web experiences

Injecting React into our code

  • we can always use create-react-app but to start with the basics , we can even import react using a simple CDN

Hello World Using Simple React

  • React is always rendered inside a root

  • The second object argument in React.createElement is used to give attributes to the tag (see above screenshot)

if we console the heading above we can see the anatomy of a react element

  • we can quickly see how creating much more complex structures using pure react can become fairly complex with increasing levels of nesting (see screenshot below)

    Adding npm to our React app

    • In order to reuse useful packages that aid our development we need npm - node package manager

    • npm init -y generates package.json for our app which is a configuration for our npm

    • React applications often consist of multiple files, including JavaScript files, CSS files, and various assets. Bundlers like Parcel or Webpack help manage these files by bundling them together into a single file or a set of files that can be efficiently served to the browser.

    • We need to install a bundler like webpack,parcel or vite ,they package our app : npm i -D parcel

    • package.json keeps track of the exact version ,and node_modules contains code of all transitive dependencies

    • package and page-lock.json must be maintained on version control but node_modules should not so we add it to .gitignore

    • npx parcel index.html : npx 'executes' an npm package , if we execute parcel it creates and development build and hosts it on a port in localhost- START COMMAND

    • npm install react: instead of getting react from cdn, its more optimised if we have react in our node_modules, it more easier for the latter approach to maintain/upgrade versions

    • npm i react-dom:

    • Parcel uses a file-watching algorithm and does hot module replacement when ANY file changes in react project, it does differential bunding of app to support old/new browsers alike, it can also give us an http server instead of a https server, it gives use separate dev and prod bundles

    • npx parcel build index.html: to create a production build (make sure to remove "main" from pacakge.json before this)- creates the build in dist folder- BUILD COMMAND

    • npm run start/ npm start build ...

Introducing JSX

parcel uses babel to transpile jsx back into valid js code

React Components

A simple js function that returns jsx

React Reconciliation / React Fiber

  • React creates a virtual DOM, which is a representation of actual DOM its uses a DIFF algorithm that finds difference between Old and new virtual DOM, and then selectively update only those components in subsequent render cycle

React Hooks Lifecycle

  • useEffect called after every render in case we don't provide the second argument, if dependency array is empty its just called once on mount and if some variable is provided inside depencey array , useEffect is called when that variable changes

Client Side React Routing

we can also handle error routes via providing a custom component in the object props

Creating children routes - Outlet

Outlet will be replaced by child routes according to the path

We can now use Link component to redirect clicks to the respective paths, this takes in a to prop as the relative page path

There two types of routing in web apps - client side routing and server side routing

Dynamic Path Routes

and now we can use the useParams hook to read the parameter passed

Additional Notes

  • React cdn must always be before any additional js script files

  • React is a library NOT a framework, it can work independently in any or all portions on your web app

  • Is safer to put karat (^) over tilda(~) with dependecies, as it wil only update minor versions and not major versions

  • package.json: This file holds metadata about the project and manages dependencies. It includes information like project name, version, entry point, scripts, and most importantly, a list of dependencies and their versions. Developers generally modify this file when adding or updating dependencies manually or through npm commands (npm install, npm uninstall).

  • package-lock.json: Introduced in npm 5, this file is automatically generated and helps in package version management. It keeps track of the exact version of each installed package and its dependencies, ensuring that installations are deterministic across different environments. It locks down the exact versions of dependencies installed by npm install, preventing unexpected version changes when moving the project between different machines or environments.

  • package.json contains metadata and dependency declarations, while package-lock.json is a detailed record of exact dependency versions installed in the project. The combination of both ensures consistent and predictable dependency management.

  • Parcel, the web application bundler, utilizes consistent hashing for efficient caching and bundle output consistency.

    • Why Consistent Hashing?: Parcel aims to optimize caching by generating consistent hash values for input files. This approach allows it to uniquely identify files based on their content. When the content changes, Parcel recalculates the hash, enabling it to detect modifications and invalidate cache selectively.

    • How React Parcel Uses Consistent Hashing:

      • File Content as Key: Parcel computes a hash based on the content of input files, including React components, JavaScript files, stylesheets, and other assets.

      • Cache Optimization: By hashing file contents, Parcel can efficiently manage its cache. Unchanged files retain the same hash value, allowing Parcel to reuse cached outputs without recomputation. When content changes, the hash changes, prompting Parcel to rebuild and update the cache.

    • Overall, consistent hashing in Parcel ensures that if the content of a React component or any file changes, Parcel can accurately identify the modification, trigger a rebuild for affected parts, and maintain a consistent caching mechanism for optimized performance during development and production builds.

    • You can go to browserlist.dev and manage the browserlist in your package.json file

    • JSX, which stands for JavaScript XML, is a syntax extension for JavaScript often used with React to describe what the UI should look like. However, JSX itself needs to be converted to standard JavaScript code for the browser to understand it. This conversion is typically done by a tool called a "transpiler."

      For React, the most common transpiler used to convert JSX to JavaScript is Babel. Babel is a widely used JavaScript compiler that can transform JSX syntax into standard JavaScript that browsers can interpret.

      Here's a simplified explanation of the process:

      1. JSX Code (React Component):

         const element = <h1>Hello, World!</h1>;
        
      2. Babel Transpilation: Babel will convert the JSX code into JavaScript:

         const element = React.createElement('h1', null, 'Hello, World!');
        

        Note: In the background, Babel relies on the React.createElement method to create React elements.

  • To use Babel for JSX transpilation, you typically set it up as part of your project's build process. You also might need additional presets and plugins, like @babel/preset-react, to enable JSX transformation.
ย