REACT.js: A library or a framework?

Introduction

REACT.js: A library or a framework?

Before diving deep into what React.js is, let’s understand the difference between a library and a framework.

A library serves as a multitalented toolbox, presenting developers with a repository of pre-written functions and utilities designed for specific tasks. In simple terms, a library acts as a helpful assistant, providing support for various aspects of development without imposing a rigid or predetermined structure. Developers are free to integrate these tools seamlessly into their projects, shaping the overall architecture according to their unique requirements whereas a framework offers a more structured approach.

We can think of it as a blueprint guiding the construction of our application. A framework not only outlines a particular structure but also imposes conventions and frequently governs the flow of control. Developers essentially integrate their code into the framework, adhering to its pre-established patterns and guidelines.

Embarking on the journey of web development, especially for beginners, often feels like navigating uncharted waters. In this vast ocean of frameworks and libraries, React.js emerges as a reliable compass, guiding newcomers through the intricacies of building dynamic and interactive user interfaces. Let's embark on an amazing exploration of React.js, from its fundamental concepts to the practical steps.

Understanding the Essence of React.js.

At its core, React.js is not merely a library; it's a philosophy that transforms the way developers conceive and construct web interfaces. Developed by Facebook, React.js revolves around the concept of components talking about which it can be defined as self-contained units of code that encapsulate specific parts of a web application.

Consider the simplicity and power of a React component:

A Glimpse into React.js Magic

import React from 'react';//This allows you to use react features imported from the react dependencies installed locally into your system. However the ".jsx" files donot require this declaration

const Greeting = ({ name }) => {

return <div>Hello, {name}!</div>;

};

Here, the Greeting component becomes an entity, rendering a personalized greeting. This functionality of components promotes reusability and maintainability, two cornerstones of efficient and scalable web development.

REACT: the GAME-CHANGER

The Declarative Symphony of React.js

React.js embraces a declarative paradigm, a stark departure from the imperative approach of manipulating the Document Object Model (DOM). Instead of providing step-by-step instructions on how to manipulate the DOM, developers declare what they want the UI to look like, and React orchestrates the rest.

This declarative approach enhances code predictability and maintainability. Consider the contrast between imperative and declarative code when updating the text of an element:

Imperative approach

document.getElementById('myElement').innerText = 'New Text';

Declarative approach in React.js

return <div>New Text</div>;

In the declarative paradigm, developers express the desired outcome, letting React handle the underlying complexity.

REACT & performance?

A Ballet of Virtual and Actual DOM

React's performance optimization is made possible by its use of a Virtual DOM. When a component's state changes, React first updates a virtual representation of the DOM before efficiently applying only the necessary changes to the actual DOM. This dance between the virtual and actual DOM results in a significant boost in application speed and responsiveness.

LET'S GET STARTED

Setting Sail: Crafting Your First React App

To set sail on your React.js adventure, you need to establish your development environment. A popular tool for this task is Create React App, which simplifies the setup process and allows you to initialize a new React project with a single command.

install npm(node package manager if not done yet)npm i -gnpx create-react-app my-first-react-app //project names should me in small case
cd my-first-react-app
npm start

In the blink of an eye, your basic React app is being setup. Dive into the src/App.js file to witness the real-time changes of your first React application as you start building over it.

Warning: Beware of bugs and enjoy your peaceful mind one last time as you embark into this journey, 'coz debugging sucks!!!

Navigating React Components: The Building Blocks of UI

React components are the fundamental building blocks of a React application. Each component encapsulates a specific piece of functionality or UI element. As your application grows, components can be reused, combined, and nested to create a modular and scalable structure.

For example, consider a simple application with a Header, Sidebar, and MainContent component:

Header component

const Header = () => <header>My App Header</header>;

Sidebar component

const Sidebar = () => <aside>My App Sidebar</aside>;

// MainContent component

const MainContent = () => <main>My App Main Content</main>;

These components can then be combined to create the overall structure of your application:

// App component combining Header, Sidebar, and MainContent

const App = () => (
<div>

<Header />

<Sidebar />

<MainContent />

</div>

);

This modular approach to building UIs enhances code readability, maintainability, and encourages the separation of concerns.

Handling State and Props: The Pulse of React Applications

In React, state and props are crucial concepts that govern the behavior and appearance of components.

State: The state represents the internal data of a component(the status or the current condition of the application). It can change over time in response to user interactions or other factors. Updating the state triggers a re-render of the component, reflecting the changes in the user interface.

Consider a Counter component with an increment button:

import React, { useState } from 'react';

const Counter = () => {

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

return (

<div>

<p>Count: {count}</p>

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

</div>

);

};

In this example, the useState hook is used to create a state variable count and a function setCount to update it. When the "Increment" button is clicked, the count state is updated, triggering a re-render.

Props: Props (short for properties) are data passed from a parent component to a child component. They allow components to communicate and share data.

// Parent component
const ParentComponent = () => {

const data = "Hello from Parent!";

return <ChildComponent message={data} />;

};

// Child component

const ChildComponent = ({ message }) => <p>{message}</p>/;

In this example, ParentComponent passes the message prop to ChildComponent, which then renders it. Props enable the flow of information between components in a React application.

ANOTHER HOOK

Enhancing Your React Arsenal: Hooks and Effects

React introduced Hooks as a way to use state and lifecycle features in functional components, making them more powerful and versatile. The useEffect hook, for example, allows you to perform side effects in functional components, such as data fetching or subscriptions.

import React, { useState, useEffect } from 'react';
const DataFetchingComponent = () => {

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

useEffect(() => {
// Fetch data when the component mounts

fetch('[https://api.example.com/data](file:///C:/Users/Admin/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml)')

.then(response => response.json())

.then(data => setData(data));

}, []); // Empty dependency array ensures the effect runs only once

return (

<div>

<h2>Data:</h2>

<ul>

{[data.map](file:///C:/Users/Admin/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml)(item => (

<li key={[item.id](file:///C:/Users/Admin/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml)}>{[item.name](file:///C:/Users/Admin/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml)}</li>

))}

</ul>

</div>

);

};

Hooks provide a concise and elegant way to manage state and side effects in functional components, offering a powerful toolset for building robust React applications.

PS: Hooks are one of the super power of React.

Till now you have had an insight about what react is, how it works and some of its major functionalities and features.However,though I won't call this much as a tip of the iceberg but still, react offers much more including styling.

Some other features of React includes:

  • Routing(Where the virtual dom kicks in)

  • Link, NavLink(No re-rendering like the anchor tag) and many more...

We can discuss about these, some other day.

Some resources for diving deep into the react.js are :

  • Youtube channels: freeCodeCamp,netninja, etc.

  • Official Documentation of React.js (Browse: "[react.dev](file:///C:/Users/Admin/AppData/Local/Temp/msohtmlclip1/01/clip_filelist.xml)")

  • And ofcourse, hashnode blogs.

Did you find this article valuable?

Support GDSC NIT Silchar Blog by becoming a sponsor. Any amount is appreciated!