- i recommend to have zoom 80% cause idk all hashnode articles's text are so enlarged/zoomed nevermind if you don't mind 😁*
REACT
Unlike other FRAMEWORKS -> React is a JavaScript LIBRARY specialized in rendering user interfaces (UI) efficiently allowing developers to choose other tools and libraries for additional functionality, making it highly flexible
Components
React applications are built from isolated pieces of UI called React component which is a JavaScript function where you can sprinkle JSX(JSX = javascript + HTML(more accurately - html inside javascript functions)) which is rendered into the browser(more on this later).
React components -> simply a function -> a building block.
JSX
JSX lets you write HTML-like markup inside a JavaScript file, keeping rendering logic and content in the same place.
JSX -> HTML tags in JavaScript code
Sometimes you will want to add a little JavaScript logic or reference a dynamic property(like a variable) inside that markup. In this situation, you can use curly braces in your JSX to “open a window” to JavaScript
import React from 'react';
function App() {
// Define a JavaScript variable
const name = 'World';
return (
// curly braces to include js logic inside html markup
<div>
<h1>Hello, {name}!</h1>
</div>
);
}
export default App;
Props and State
React components use props to communicate with each other. Every parent component can pass some information to its child components by giving them props.
Props -> messages from parent to child
The useState
Hook lets you declare a state variable. It takes the initial state and returns a pair of values: the current state, and a state setter function that lets you update it.
State -> memory for a component*.
Hooks are special functions that let your components use React features (useState is one of those features). It's a naming convention that hooks start with use like useSomething
.
const [count, setCount] = useState(0);
Event Handling
React lets you add event handlers to your JSX. Event handling in React allows you to respond to user interactions (like clicks or keyboard input). You define functions to run when events occur
Event Handling -> reacting to user actions.
Built-in components like only support built-in browser events like onClick.
// here handleIncrement() function is triggered/called
<button onClick={handleIncrement}>Click me</button>
Here's an example that includes everything discussed so far...
import React, { useState } from 'react';
// Functional Component
function Counter(props) {
// Using the useState hook to manage state
const [count, setCount] = useState(0);
// Event handler function to update the count by 1
const handleIncrement = () => {
setCount(count + 1);
};
return (
<div>
// Displaying the title received via props
<h2>{props.title}</h2>
<p>Count: {count}</p>
<button onClick={handleIncrement}>Increment</button>
</div>
);
}
// Parent Component
function App() {
return (
<div>
<h1>React Components, useState, and Props</h1>
// Using the Counter component and passing a title prop
<Counter title="Click Counter" />
</div>
);
}
export default App;
DOM (Document Object Model)
DOM is a programming interface for web documents. It represents the structure of an HTML document and allows programs (like JavaScript) to manipulate the DOM, interact with the web page, handle user interactions, and perform various tasks to enhance the functionality and interactivity of the web page.
DOM -> a map of your webpage that programs can read and change.
Rendering and Reconciliation
Rendering -> creating a picture of your UI
Reconciliation -> updating that picture efficiently.
Imagine rendering as painting a picture of your room, and reconciliation is making changes to that picture without repainting the entire room.
JSX is not directly understood by web browsers. React, along with tools like Babel, handles the transpilation (translated) of JSX into plain JavaScript.
The transpiled JavaScript code, whether it's embedded within HTML script tags or linked from external files, is executed by the browser's JavaScript engine.
Reconciliation is the process through which React updates the Browser DOM.
In traditional rendering, Browser does the following tasks:
- Creates a DOM (Document Object Model) represented by a tree structure
- Renders any new data to the DOM even if data is similar to previous ones. This rendering by Browser has a sequence of steps and is rather costly in nature.
Virtual DOM
Virtual DOM used by React to render JSX components to the Browser DOM, but keeps a copy of the actual DOM to itself. This copy is the Virtual DOM.
- When we make changes or add data(for example lets say a state is updated) React creates a new Virtual DOM and compares it with the previous one.
- Comparison is done by Diffing Algorithm. (Breadth-First Search (BFS) is used because it will re-render the entire subtree hence Depth First Approach is not exactly optimal. -> i will post DSA stuff too soon like never before - hopefully🤞)Then it updates the Browser DOM with the least number of changes possible without rendering the entire DOM again unlike traditional rendering. This changes the efficiency of an application tremendously.
Hooks
Hook were introduced to functional components for more concise functional components to do what class components could do, avoiding the often verbose and complex class-based component structure(which were used in previous react versions).
useState
declares a state variable that you can update directly.useEffect
this basically triggered after the component is rendered so used to connect with external systems.useContext
lets a component receive information from distant parents without passing it as props.useRefs
let a component hold some information that isn’t used for rendering,useMemo
lets you cache the result of an expensive calculation. And some more...
We can create Custom Hooks which are basically JavaScript functions that encapsulate reusable logic and stateful behavior, allowing you to share this logic across multiple components.
Custom Hooks -> reusable logic functions used by other componentsHooks are like superpowers you can use (
use
get it?😂) to components
Here's how we can use customHook to encapsulate stateful logic in useCounter
used in CounterComponent
import React, { useState } from 'react';
// Custom hook for managing a counter
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => {
setCount(count + 1);
};
const decrement = () => {
setCount(count - 1);
};
return { count, increment, decrement };
}
// Component using the custom hook
function CounterComponent() {
// Using the custom hook to manage the counter state
const { count, increment, decrement } = useCounter(0);
return (
<div>
<h1>Counter: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
}
export default CounterComponent;
Higher-Order Components (HOCs)
In React, a higher-order component is a function that takes a component as an argument and returns a new component with some additional functionality that wraps the original component without modifying the actual component's code.
we can Add stuff like
Authentication called withAuth
Logging withLogger
Styling and Theming - withTheme
[NOTE]
you guys ever seen or used HOC anywhere? because its I'm about as familiar as Sheldon Cooper is about sarcasm...
Server-Side Rendering (SSR)
React, by default, performs Client-Side Rendering (CSR), where the majority of rendering and data fetching occurs on the client's side. On the other hand, Server-Side Rendering (SSR) generates the complete HTML for the page, including its content, on the server.
Next.js simplifies SSR by providing next *get it?😂* level solution, making it a popular choice for server-side rendering in React projects *which is the next post get it again?😂ok this is last i promise*
it's important to note that React is primarily a UI LIBRARY and not a all-in-one FRAMEWORK so developers often integrate other libraries/tools to address other aspects of web development like state management, routing, navigation, and data fetching from APIs and more. Adds more flexibility for us.
State Management
It provides a central place to store and update data, eliminating the need to pass data through multiple components which avoids a practice known as "prop drilling”.(drilling props to lot of components)
State management -> central hub to manage and share data, eliminates prop drilling.
Some popular choices include Zustand, recoil, redux...
Routing and Navigation
Routing and navigation allows users to move between different parts of the app, with the aspiration to make a multi-page experience in a single-page application (SPA).
The most popular routing library for React include React Router...
Fetching Data from External Sources/Working with APIs
Data fetching in React involves retrieving data from external sources, often using web APIs (Application Programming Interfaces) which allow our web application to communicate with external servers or databases to fetch/retrieve, update, or i should say to manipulate data simply🤦♂️.
These tools are commonly used for data fetching and communication with APIs
- The built-in
fetch()
function in JavaScript(i just came to know that this exists while using Nextjs🤦♂️poor me). - Axios: A popular third-party library for making HTTP requests with additional features and ease of use.
- GraphQL: A query language and runtime for APIs that allows clients to request exactly the data they need.
- React Query - does Data Fetching on top of it also does State Management, Caching, Automatic Refetching, Pagination and Infinite Loading, Optimistic Updates, Server-Side Rendering (SSR) Support.
[NOTE] Hit me up with your ideas on what topic to conquer next(probably next)! Consider me a coding genie ready to grant your wish! 🧞♂️. Let that be something niche and hardcore! 💪👾 and not a typical topic like React so i can simplify it to the utmost simplicity