Page 1 of 19
React is a JS library. It shows content (HTML) to users and user interaction.
React
- React: Knows what a component is and how to make components work together.
- ReactDOM: Knows how to take a component and make it show up in the DOM.
Flow of Creating a React App
graph TD;
create-react-app --> JSX_Project;
JSX_Project --> Webpack;
JSX_Project --> Babel;
JSX_Project --> Dev_Server;
Dev_Server --> Dependencies;
ES2015 Modules vs CommonJS Modules
- ES2015 Modules: Use
import. - CommonJS Modules: Use
require.
Definition of a Component
A component is a function or class that produces HTML and handles data to show the user.
Using ReactJS
- Import the React & ReactDOM libraries.
- Create a React component.
- Take the React component and show it on the screen.
Page 2 of 19
JSX Syntax
const App = () => {
return <div>Hi there</div>;
};
This is equivalent to:
React.createElement("div", null, "Hi there");
Key Points About JSX:
- JSX is a special dialect of JS (it's not HTML).
- It is similar in form to HTML.
- JSX is compiled to JS.
JSX vs HTML
Adding Custom Styling to an Element
HTML Example:
<button style="background-color: red; display: block;">Button</button>
JSX Example:
<button style={{ backgroundColor: 'red', display: 'block' }}>Button</button>
Adding a Class to an Element
HTML Example:
<div class="btn"></div>
JSX Example:
<div className="btn"></div>
Page 3 of 19
Using Variables in JSX
const text = buttonText;
buttonText: Name of the variable.- It cannot be an object; it needs to get value.
Example:
const getButtonText = () => {
return "Click Me!";
};
Additional Notes:
- JSX prevents injection attacks.
- Example of differences:
label for→label htmlFor.
Communicating with Props
Three Tenets of Components:
-
Component Nesting
A component can be shown inside another. -
Component Reusability
We want to make components that can be easily reused. -
Component Configuration
We should be able to configure a component when it is created.
Component Hierarchy Diagram
graph TD;
Parent[App] --> Child1[CommentDetail];
Parent --> Child2[CommentDetail];
Parent --> Child3[CommentDetail];
Page 4 of 19
Props
Definition:
Props are the system for passing data from a parent component to a child component. They are read-only.
Example:
<CommentDetail author="Sam" />
In the component:
function CommentDetail(props) {
console.log(props.author);
}
Component Reuse
Example:
<ApprovalCard>
<CommentDetail author="Ya" />
<CommentDetail author="Hey" />
</ApprovalCard>
Explanation:
props.children: Can be an array of single elements.- Access individual children:
props.children[0] props.children[1]
Class-Based Components
- Simple Components → Function Components
- Everything Else → Class Components
Page 5 of 19
Easier Code Organization
- Class Components:
- Can use
state(Modern React system)- Easier to handle user input.
- Understands different events.
- Easier to do things when the app starts.
- Can use
Rules of Class Components
- Class React (Must be a JS class).
- Must extend
React.Component. - Must define a
render()method that returns some amount of JSX.
Rules of State
- Only usable with class components (
technically can be used with→ corrected: works only with class components system). Stateis a JS object that contains data relevant to a component.- Updating
stateon a component causes the component to instantly re-render. Statemust be initialized when a component is created.- State can only be updated using the function
setState().
Conditionally Rendering Content
if (...) {
return <div></div>;
}
Page 6 of 19
Component Lifecycle
graph TD A[Constructor] --> B[Render] B --> C[ComponentDidMount] C --> D[ComponentDidUpdate] D --> E[ComponentWillUnmount]
- Constructor:
- Good to do one-time setup.
- Render:
- Returns JSX, try to avoid anything else.
- ComponentDidMount:
- Good to do data-fetching.
- ComponentDidUpdate:
- Set & wait while this component is updated to perform actions.
- ComponentWillUnmount:
- Good to do cleanup.
Component Initialization
constructor(props) {
super(props);
this.state = {};
}
OR
state = {};
Passing Arguments to Event Handlers
<button onClick={this.handleClick.bind(this, id)}>
Click Me
</button>
OR
<button onClick={(e) => this.handleClick(id, e)}>
Click Me
</button>
Page 7 of 19
Redux
- It is a state management library.
- Makes creating complex applications easier.
- Not required to create a React app.
- Not explicitly designed to work with React.
Redux Cycle
graph TD A[Action Creator] --> B[Action] B --> C[Dispatch] C --> D[Reducers] D --> E[State]
Example Flow
graph TD A[Form Displaying on the Screen] --> B[User Filling the Form] B --> C[Action Triggered] C --> D[Reducers] D --> E[Combined & Processed Data]
Page 8 of 19
Webpack
Why?
- We usually have several JS & CSS files in a single HTML without any knowledge of dependencies.
- Some tools like
GruntandGulpbundle all JS files into one but couldn't manage all dependencies. Require.jscould help but it was not as powerful.
What is Webpack?
- Webpack is a static module bundler for modern JS applications.
(Note:create-react-appuses Webpack). - It can handle JS, TS, CoffeeScript, CSS, SASS, LESS, images, and so much more.
Loaders
Used to import various different files like img, CSS, etc.
module: {
rules: [
{
test: <regex>,
use: [<loader-to-use>]
}
]
}
- Note: Processes from right to left.
Page 9 of 19
Config
- Entry: (Begin Point)
- Output:
path: `<absolute_path>`, filename: `bundle.js`, publicPath: `dist` // (Used for CDN)- Notes:
- Use hash to avoid browser caching.
- Example:
bundle: `[contenthash].js`, name: `[fullhash].js`
- Notes:
Babel Loader
- Test:
test: /\.js$/, exclude: `/node_modules/`, use: { loader: 'babel-loader', options: { presets: ['@babel/env'], plugins: ['transform-class-properties'] } }- Placeholder: (Unclear text at the bottom of this section)
Plugins
- Definition: Additional JS libraries that do everything loaders cannot do.
- Examples:
- Minify JS →
Terser Webpack Plugin - Minify CSS →
Mini CSS Extract Plugin
- Minify JS →
- Other Plugins:
- Clean Webpack Plugin → Cleans dist folder.
- Copy File Plugin → Copies files directly to dist folder (used for JSON).
- HTML Webpack Plugin → Ensures CSS and JS are added with hashes in filenames.
- Examples:
Page 10 of 19
Mode (Production vs Development)
- Production (by default):
- Contains:
- Terser.
- Contains:
- Development:
- Webpack dev-server:
- Improves dev experience.
- Includes:
- Hot reload.
- Source maps.
- Webpack dev-server:
Page 11 of 19
GraphQL
Architecture (Introduction)
- GraphQL can be thought of as a new API standard that provides a more efficient, powerful, and flexible alternative to REST.
REST vs GraphQL
- REST:
- Typically gathers data by accessing multiple endpoints:
GET /users/<id> GET /users/<id>/posts GET /users/<id>/followers
- Typically gathers data by accessing multiple endpoints:
- GraphQL:
- Sends a single query to the server that includes the concrete data requirements:
query { user(id: "xyz") { name posts { title } followers(last: 3) { name } } }
- Sends a single query to the server that includes the concrete data requirements:
Core Concept
The Schema Definition Language (SDL)
- GraphQL uses a type system to define the schema of an API.
- The system for creating schemas is called SDL.
Page 12 of 19
Core Concept (continued)
Example Schema:
type Person {
name: String!
age: Int!
pets: [Pet!]!
}
type Pet {
title: String
author: Person
}
Fetching Data with Queries
{
allPersons {
name
}
}
Queries with Arguments:
{
allPersons(last: 2) {
name
}
}
Writing Data with Mutations
Operations: Create, Update, Delete
mutation {
createPerson(name: "SK", age: 3) {
name
age
}
}
- Creates a person object with the specified fields.
Page 13 of 19
Realtime Updates with Subscriptions
Subscription
subscription {
newPerson {
name
age
}
}
Defining a Schema
Type Query
type Query {
allPersons: [Person!]!
}
Query with Arguments
type Query {
allPerson(class: Int): [Room!]!
}
Type Mutation
type Mutation {
createPerson(name: String!, age: Int!): Person!
}
Type Subscription
type Subscription {
newPerson: Person!
}
Architecture
There may be 3 types of architectures that represent major use cases of GraphQL and demonstrate the flexibility in terms of the context where it can be used:
Page 14 of 19
1. GraphQL Service with a Connected DB
graph TD
PC -->|Client| Server
Server -->|GraphQL Query| DB
DB -->|SQL or NoSQL| Server
2. GraphQL Layer that Integrates Existing Systems
graph TD
Client --> GraphQL
GraphQL -->|Legacy System| LegacySystem
GraphQL -->|Microservice| Microservice
GraphQL -->|Third-party API| ThirdPartyAPI
3. Hybrid Approach with Connected DB & Integration
graph TD
Client --> GraphQL_DB
GraphQL_DB -->|Legacy System| LegacySystem
GraphQL_DB -->|Third-party API| ThirdPartyAPI
Page 15 of 19
NEXT.JS
React - Frontend Library
NextJS - Framework built on React for large-scale web apps.
It contains a lot of libraries.
Features:
- Server-side rendering (helps in SEO).
- File-based routing (for React, use URL routes).
but cumbersome→ corrected: without complexity.
- Full stack capabilities (can write backend code like FS, Databases, Auth, etc.).
File-Based Routing:
- Command to initialize:
npx create-next-app
Traditional React Apps:
- React Router DOM (code-based routing).
NextJS:
Uses folder structure for routing:
index.js→ Main route./api→ Sub-path.[id].js→ Dynamic path (you can make folders as well).- Create files in
/pagesfolder.
Functional Components:
Use useRouter hook to get dynamic routes:
import { useRouter } from 'next/router';
Shallow Routing:
Can use shallow routing to avoid data fetching methods:
<Link href="/route" shallow>
Page 16 of 19
Server-Side Rendering
SEO Problems:
- Local/Spinners users cannot visit the page initially.
Workflow:
sequenceDiagram
participant Request
participant Server
participant Browser
Request ->> Server: Fetch pre-rendered page
Server ->> Browser: Return pre-rendered page
Browser ->> Browser: Hydrate (on React load)
SEO-friendly, as the page is interactive.
Two Forms of Pre-Rendering:
- Static Generation
- Server-side Rendering
Static Generation:
Pre-generate a page during build time.
Pages are prepared ahead of time & can be cached by the servers serving the app (current values & dynamic values).
Example Function:
function getStaticProps(context) {
return {
props: {
posts: [1, 2, 3],
notFound: true,
redirect: '/home',
},
};
}
This object is sent to React components (function components).
Server Code:
You can use server code in this function. Build will get data, pre-render, & render the app page.
no SEO → corrected: SEO-friendly.
Page 17 of 19
Notes on Next.js
Note 1
-
It doesn’t really run on the server, it runs during build time.
-
So, if you have data that changes frequently, it won’t work very well.
-
Use
revalidateingetStaticProps, which will regenerate the page & then the client can have an updated page.
Notes
-
Dynamic pages are not pre-generated by default in Next.js.
-
Example function:
function getStaticPaths() { return { paths: [ { params: { pid: 'p1' } }, { params: { pid: 'p2' } }, ], fallback: false // If set to true, pre-generated pages are just-in-time. // If set to "blocking", wait till generation is complete. }; }
II. Server-Side Rendering
-
For every incoming request, this function gets executed.
-
Example function:
function getServerSideProps(context) { return { props: { username: 'Max' // Access to context request & response object } }; }
Page 18 of 19
Semi-data Handling
-
Semi-data doesn’t need to be pre-rendered.
-
Characteristics:
- Data changes with high frequency.
- Highly user-specific data.
- Pooled data.
-
Solution:
- Use Next.js SWR hooks (good features for revalidation on focus or revalidation on interval).
function useData() { const { data, error } = useSWR(); if (!data) { return <Loading />; } if (error) { return <Error />; } return <Content />; }
Optimizing Next.js Apps
I. Head Metadata
- Head from
next/head_app.js: Common settings for all pages._document.js: Customize HTML document.
II. Optimizing Images
- Image from
next/image- Optimize images by making edits to
width,height,OS, etc. - Lazy loading.
- Optimize images by making edits to
Page 19 of 19
API Routes
-
Create API routes easily with Next.js.
-
Example function:
function handler(req, res) { res.status(200).json({ message: 'API response' }); } -
You can add dynamic routes as well using query parameters (
req.query.id).
Deployment
-
next build: Optimized app for production.- Files generated:
next/static/chunks/pages: File-based routed pages.next/static/media: Handled images fromnext/image.next/static/css: Critical CSS.next/server/pages: API pages.next/server/chunks: Shared JS chunks.next/cache: Build cache, cached images, responses, and pages.
- Files generated:
-
For client apps:
- Use
next export.
- Use
-
Configuration:
next.config.js: Configure dev and production environments.
References & Related Topics
- React Official Documentation
- JSX
- Props in React
- Redux Documentation: https://redux.js.org
- Webpack Documentation: https://webpack.js.org
- Next.js Documentation