Unit 17 ReactJS Student's Guide
Unit 17 ReactJS Student's Guide
1st.
2024 - 2025
تطوير المواقع والبرمجيات
Unit 17 ReactJS
الصف الثالث
2
Unit 17
ReactJS
Unit 17
Name ReactJS
Goals / By the end of this Unit, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts, history, and uses of React.js,
including the Virtual DOM, React components, state,
props, hooks, and routing.
2. Identify the advantages and differences of React
components, Hooks, and React Router.
➢ Understanding
1. Explain the principles of React, including how it integrates
with the Virtual DOM and the importance of state and
props in building dynamic UIs.
2. Describe the use and differences between functional and
class components, state management techniques, and the
purpose of different Hooks (useState, useReducer,
useContext, useEffect).
3. Understand client-side vs. server-side rendering and how
React Router manages routing in single-page applications.
➢ Applying
1. Set up a React development environment and create basic
React applications using create-react-app.
2. Implement and manage state in functional and class
components using useState, useReducer, and useContext.
3. Create and render React components, establishing parent-
child relationships and passing data through props.
4. Use React Router to create a multi-route single-page
application with navigation and dynamic routes.
3
5. Apply various styling methods (CSS Modules, inline
styles, JavaScript objects) and integrate third-party
libraries like Bootstrap.
6. Utilize useEffect for managing side effects and component
lifecycle events.
➢ Analyzing
1. Analyze the role of the Virtual DOM in performance, and
compare functional and class components.
2. Evaluate the differences and appropriate use cases for
useState vs. useReducer.
3. Compare the advantages and implications of using SSR vs.
CSR in React applications.
4. Examine the impact of different routing and state
management techniques on application behavior and
structure.
➢ Evaluating
1. Assess the suitability and impact of using React.js, Hooks,
and React Router for different types of projects.
2. Evaluate the benefits of various state management
approaches and the use of useContext for sharing state
across components.
3. Judge the effectiveness of React Router in managing
single-page applications and the pros and cons of SSR and
CSR.
➢ Creating
1. Build a dynamic React application that utilizes
components, state, props, and Hooks for interactivity and
state management.
2. Design complex component hierarchies with effective state
sharing using useContext.
3. Develop a single-page application with multiple routes,
dynamic navigation, and SSR using React Router.
4. Implement a state-sharing mechanism and lifecycle
management using various Hooks (useState, useReducer,
useContext, useEffect).
4
Code Description
TPK20 writing asynchronous code using various
techniques
Knowledge TPK21 Basic routing and calling a controller method
from a route
TPK22 Analyze and solve common web applications
tasks by writing PHP programs
Code Description
TPC5.4 Using UI Framework (React)
Skill TPC5.5 Creating an authentication system for your
application
TPC5.7 Using controllers and routes for APIs and URLs
5
Unit Preface
6
Lesson 1
Name Introduction to React
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts of React.js and its history.
2. Identify the uses and applications of React.js.
3. List the advantages of the Virtual DOM and the
components of a React development environment.
➢ Understanding
1. Explain what React.js is and why it is widely used in
web development.
2. Describe how React.js integrates with the Virtual DOM.
3. Understand the differences between React.js and React
Native, including their specific use cases.
➢ Applying
1. Install Node.js and set up a new React app using the
create-react-app tool.
2. Write and execute a basic "Hello World" application
using React.js.
3. Use JSX to create simple React components and render
them in the browser.
➢ Analyzing
1. Analyze the role of the Virtual DOM in React.js and
how it improves performance.
2. Compare React.js with other JavaScript libraries or
frameworks in terms of component-based architecture
and performance.
➢ Evaluating
1. Assess the performance advantages of using React.js
with the Virtual DOM in web applications.
2. Evaluate the suitability of React.js and React Native for
different types of projects, including web and mobile
applications.
➢ Creating
7
1. Develop and design basic React components using JSX
to build dynamic web content.
2. Create a simple React application that utilizes
component-based architecture and demonstrates the use
of the Virtual DOM.
8
Lesson One: Introduction To React
9
Section 1: Introduction ReactJS
10
Component-Based Architecture: ReactJS developers can build
reusable UI components that can easily be combined to create complex
web applications. This modular approach to UI design makes it easier to
maintain code and speed up development time.
2. Virtual DOM: ReactJS uses a virtual DOM (Document Object
Model) that updates only the parts of the DOM that need to be updated
whenever a change occurs. This approach results in faster rendering
times and better application performance,
3. Declarative Syntax: ReactJS uses a declarative syntax, which makes
it easier for developers to understand and maintain code. This syntax
enables developers to write code that describes exactly how the UI
should look rather than writing code that manipulates the UI directly.
4. Server-Side Rendering: ReactJS can be used for server-side
rendering, which improves the initial load time of a web application and
makes it easier for search engines to index the application.
5. Large Ecosystem: ReactJS has a large ecosystem of third-party tools
and extensions, making it a great choice for all projects regardless of its
size.
11
The world’s most widely used web frameworks among developers
(source Statista 2024)
Section 2 The Virtual DOM
2-1 Virtual DOM concept
The Virtual DOM is a programming concept used in modern JavaScript
frameworks like React and Vue.js. It's a lightweight, in-memory
representation of the actual DOM (Document Object Model) of a web page.
12
2. Updates: When the component's state or props change, the
framework updates the virtual DOM.
3. Diffing: The framework compares the old and new virtual DOMs to
identify the minimal set of changes needed to update the actual
DOM.
4. Patching: The framework applies the necessary changes to the actual
DOM, updating only the affected parts.
13
Section 3 Getting Started with React.js:
3-1 Installing Node.
Now, let’s take the first step into the world of React.js and set up our
development environment.
• Installing Node.js and npm: Before we begin, make sure you have
Node.js and npm (Node Package Manager) installed on your system.
You can download and install the latest version from the official
Node.js website : Download Node.js
• Creating a New React App: Once Node.js and npm are installed, open
your terminal or command prompt. Use the following command to
create a new React app
3-2 Creating a New React App
npx create-react-app my-react-app
This will set up a new React.js project with the name "my-react-app" in
your current directory.
Starting the Development Server: Change your working directory to the
newly created project folder using the "cd" command:
cd my-react-app
14
To see your "Hello World" application in action, start the development
server with the following command:
npm start
Your React.js application will now be accessible at "http://localhost:3000"
in your web browser.
15
Section 5 JSX In ReactJS?
5-1 What is JSX?
JSX is a syntax extension for JavaScript that allows you to write HTML-
like code within JavaScript files. It is not a template language but rather a
preprocessor that gets transformed into regular JavaScript code before it's
executed.
16
Section 6 Difference between ReactJS and React Native
6-1 ReactJS
ReactJS is an open-source JavaScript library used to build the user interface
for Web Applications. It is responsible only for the view layer of the
application. It provides developers to compose complex UIs from a small
and isolated piece of code called "components." ReactJS made of two parts
first is components, that are the pieces that contain HTML code and what
you want to see in the user interface, and the second one is HTML
document where all your components will be rendered.
Advantage of ReactJS
1. Easy to Learn and Use: ReactJS is much easier to learn and use.
Any developer who comes from a JavaScript background can easily
understand and start creating web apps using React.
2. Creating Dynamic Web Applications Becomes Easier: To create a
dynamic web application specifically with HTML was tricky, which
requires complex coding, but React JS solved that issue and makes it
easier. It provides less coding and gives more functionality.
3. Reusable Components: A ReactJS web application is made up of
multiple components, and each component has its logic and controls.
These components can be reused wherever you need them. The
reusable code helps to make your apps easier to develop and maintain.
17
4. Performance Enhancement: ReactJS improves performance due to
virtual DOM. The React Virtual DOM exists entirely in memory and
is a representation of the web browser's DOM. Due to this, when we
write a React component, we did not write directly to the DOM.
Instead, we are writing virtual components that react will turn into the
DOM, leading to smoother and faster performance.
5. The Support of Handy Tools: ReactJS supports a handy set of tools
which make the task of the developers understandable and easier. It
also allows you to select components and examine and edit their
current Props and State.
19
Terminology:
• React.js (ReactJS): A JavaScript library by Facebook for building
UIs in single-page apps using reusable components.
• Virtual DOM: An in-memory version of the DOM used by ReactJS
to optimize rendering by updating only changed elements.
• JSX (JavaScript XML): A syntax for writing HTML-like code in
JavaScript files, transformed into standard JavaScript before running.
• React Native: A framework for building mobile apps for iOS,
Android, and Windows using native components.
20
Dear learner: Put "True" in front of the correct statement and "False" in front
of the incorrect statement.
No Question Answer
21
c) User interfaces for web applications
d) Database management
10 Which concept is the core of ReactJS?
a) Middleware
b) Virtual DOM
c) MVC architecture
d) JavaScript templates
11 What is JSX?
a) A new programming language
b) A syntax extension for JavaScript
c) A database query language
d) A version of HTML
12 ReactJS can be used for which of the following?
a) Only mobile applications
b) Only web applications
c) Both web and mobile applications
d) Only desktop applications
13 Which command is used to create a new React.js
application?
a) npm create-react-app
b) create-react-project
c) npx create-react-app
d) react-init
14 What feature of React helps optimize the performance of
UI updates?
a) Real-time Database
b) Virtual DOM
c) Stateful Components
d) REST API
22
15 React Native is used to build:
a) Web applications
b) Desktop applications
c) Mobile applications
d) None of the above
16 Which of the following is true about React.js?
a) It uses two-way data binding
b) It is based on reusable components
c) It is designed for back-end development
d) It doesn't use JavaScript
23
Lesson 2
Name Rendering UI with React
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Recall the basic concepts and types of React
components.
2. Identify the advantages of using React components.
3. List the methods for styling React components,
including CSS Modules, inline styles, and global styles.
➢ Understanding
1. Explain what React components are and their
importance in building UIs.
2. Describe the differences between functional and class
components in React.
3. Understand the parent-child relationship in React
components and how data is passed through props.
➢ Applying
1. Create and render functional and class components in a
React application.
2. Use parent-child relationships to build nested React
components.
3. Apply different styling methods (CSS Modules, inline
styles, JavaScript objects, and global styles) to React
components.
➢ Analyzing
1. Analyze the differences between functional and class
components, and determine when to use each.
2. Compare the various methods of styling React
components and their impact on component isolation
and reusability.
➢ Evaluating
1. Assess the advantages of using React components for
creating reusable and maintainable UI elements.
24
2. Evaluate the use of Bootstrap with React and its
methods of integration (using a CDN and package
manager).
➢ Creating
1. Develop React components using both functional and
class-based approaches.
2. Design a React application that uses parent-child
relationships to pass data and render complex UIs.
3. Implement styling for React components using CSS
Modules, inline styles, JavaScript objects, and global
styles.
4. Integrate Bootstrap into a React application using a
CDN or package manager.
writing asynchronous code using various
TPK20
techniques
Knowledge
Analyze and solve common web applications
TPK22
tasks by writing PHP programs
Code Description
Skill TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs
25
Lesson Two: Rendering UI with React
26
Section 1: React COMPONENT
1-1 Understanding Components
React components are the building blocks of a React application. They are
like custom HTML elements that you can reuse throughout your app.
A Component is one of the core building blocks of React. In other words,
we can say that every application you will develop in React will be made
up of pieces called components. Components make the task of building UIs
much easier.
Here we can see a UI broken down into multiple individual pieces called
components and work on them independently and merge them all in a
parent component which will be your final UI.
27
Section 2 Types of Components in React
In React, we mainly have two types of components:
• Functional Components
• Class based Components
2-1 Functional Component in React
Functional components are just like JavaScript functions that accept
properties and return a React element.
We can create a functional component in React by writing a JavaScript
function. These functions may or may not receive data as parameters, we
will discuss this later in the tutorial. The below example shows a valid
functional component in React:
Syntax:
function demoComponent() {
return (<h1>
Welcome Message!
</h1>);
}
Passing Props:
• Parent components can pass data to their child components as props.
• Props are immutable values that are passed down from parent to child
components.
• Child components can access and use these props to render their own
UI.
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
30
function WelcomeMessage(props) {
return (
<div>
<Greeting name={props.name} />
<p>Welcome to our website!</p>
</div>
);
}
In this example, the WelcomeMessage component is the parent component,
and the Greeting component is the child component. The WelcomeMessage
component passes the name prop to the Greeting component, which is then
used to render the greeting message.
31
Section 4 Styling React components using CSS
32
function MyComponent() {
return (
<div style={{ color: 'red', fontSize: '24px' }}>
My Component
</div>
);
}
4-3 JavaScript Object
You can also create an object with styling information, and refer to it
in the style attribute:
function MyComponent() {
const style = { color: "red", backgroundColor: "yellow" };
return (
<div >
<h1 style={style}> Welcome From Component </h1>
</div>
);
}
33
Section 5 Using Bootstrap with React
how to use React and Bootstrap, and how to add bootstrap to React app.
34
Terminology:
• React Components: Reusable building blocks of a React app, acting
like custom HTML elements.
• Functional Components: Simple JavaScript functions that return
React elements. Ideal for static UI elements.
• Class Components: More complex components using ES6 classes.
They manage their own state and show inheritance.
• Props: Immutable data passed from parent to child components, used
to render dynamic content.
35
Dear learner: Complete the question.
No. Question Answer
21 The Virtual DOM compares the old and new DOMs
to identify ______.
22 ReactJS is based on a ______ architecture, where
components can be reused.
23 A syntax extension in ReactJS that allows embedding
HTML-like code in JavaScript files is called ______.
24 ______ is used for developing Mobile applications.
36
Dear learner: Put "True" in front of the correct statement and
"False" in front of the incorrect statement.
No Question Answer
29 React components can be nested within other
components.
30 Props are mutable and can be changed within a child
component.
31 A class component must extend React.Component.
32 Functional components can access and modify the state
without using hooks.
33 CSS Modules are used to avoid global CSS conflicts by
scoping styles to components.
34 You cannot use inline styles directly in JSX elements.
35 State is unique to each component and cannot be
accessed by other components directly.
36 Prop drilling refers to passing props from parent to
child through multiple layers.
37 React.memo is used to prevent unnecessary re-renders
of functional components.
38 You can only use state in functional components, not in
class components.
37
b) Global state management
c) Reusability and maintainability
d) None of the above
38
Lesson 3
Name State Management
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Define state and props in React.
2. Identify the need for state management in React.
➢ Understanding
1. Explain how state is used in functional and class
components.
2. Describe the difference between state and props.
➢ Applying
1. Use useState in functional components.
2. Implement state in class components using this.state and
setState.
3. Pass and use props in child components.
➢ Analyzing
1. Compare state usage in functional vs. class components.
2. Analyze how to lift state up to manage shared data.
➢ Evaluating
1. Assess the importance of state management in larger
React apps.
2. Evaluate techniques for managing state and props in
component hierarchies.
➢ Creating
1. Create React components using state and props for
dynamic UIs.
2. Design component hierarchies with effective state and
props management.
39
TPK20 writing asynchronous code using various
techniques
TPK21 Basic routing and calling a controller method
from a route
Code Description
Skill
TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs
40
Lesson Three: State Management
41
Section 1 What Is State and Props
React is a popular JavaScript library for building user interfaces. Managing
state and props, which allow components to store and pass data. we will
explore what state and props are, their differences, and how to use them
effectively in React.
42
React applications are built using components and they manage their state
internally and it works well for applications with few components, but
when the application grows bigger, the complexity of managing states
shared across components becomes difficult.
Here is a simple example of an e-commerce application, in which the status
of multiple components will change when purchasing a product.
• Add that product to the shopping list
• Add product to customer history
• trigger count of purchased products
If developers do not have scalability in mind, then it is hard to find out what
is happening when something goes wrong. This is why you need state
management in your application.
43
In this example, we define a state variable called count and its
corresponding update function, setCount, using the useState hook. The
initial value of count is 0. In addition, we can then use the count variable
within the component’s JSX to render the current count value.
To update the state, we call the update function (setCount) and provide the
new value. In the increment function, we update the count by incrementing
it by 1. React will re-render the component with the updated state,
reflecting the changes in the UI.
It’s important to note that updating state is an asynchronous operation in
React.
Meanwhile, When the update function is called, React queues the state
update and performs a batch update to minimize re-renders. This helps
optimize performance.
State is local to a component, meaning it is not accessible or modifiable
from other components. If you need to share state between components,
you can lift the state up to a common ancestor component or use state
management libraries like Redux or Context API.
44
State management in class components follows a similar concept but uses
the this.state object and the setState method to update the state. Moreover
Class components provide lifecycle methods like componentDidMount and
componentDidUpdate that allow you to handle state initialization and
updates.
State is a crucial aspect of React that enables components to have
dynamic behavior and respond to user interactions. By managing state
effectively, you can create responsive and interactive user interfaces in
your React applications.
45
2-1 What are Props?
Props (short for properties) are a way to pass data from a parent component
to its child components. Unlike state, props are immutable and cannot be
changed within the child component. They are passed down as attributes to
child components and are accessible as read-only values. We’ll explore
how to pass props and access them within functional and class components.
Basically, Props allow components to be reusable, as they can receive
different data and render accordingly based on the provided props.
The child component receives the props as an argument and can access
their values. Here’s an example:
46
Props are read-only, meaning that they cannot be modified or reassigned
within the child component.
Props are meant to be used as immutable data that influences the rendering
and behavior of the child component. If the parent component updates the
props, the child component will be re-rendered with the updated values.
Props can be of any data type, including strings, numbers, Booleans,
objects, or even functions. In addition, they can also include other React
components, allowing for nested and composition-based component
structures.
Props in React allow for the passing of data from parent to child
components, enabling component reusability and flexibility. By utilizing
props effectively, you can create modular and customizable components
that compose together to build complex user interfaces.
2-2 Managing State and Props in Component Hierarchy:
In larger applications, components are organized into a hierarchy, where
parent components pass data to child components via props. We’ll discuss
how to handle state and props in component hierarchies, including best
practices for managing and updating data flow between components.
47
2-3 Updating State and Triggering Re-renders:
Additionally, react components re-render when there are changes in their
state or props. We’ll learn about the React reconciliation process, how state
updates trigger re-renders, and how to optimize performance by using
shouldComponentUpdate or React.memo.
48
2-4 Avoid Prop Drilling:
However, Prop drilling in React refers to the practice of passing down data
or functions through multiple layers of nested components in order to make
it available to a lower-level component that needs access to it.
Consequently, Prop drilling can lead to code that is difficult to read,
understand, and maintain. To avoid theis porblem, you can use contex
or Redux. This provides a more centralized way to manage data across
multiple components.
50
44 Which of the following is true for CSS modules in
React?
a) CSS modules scope styles globally.
b) CSS modules scope styles locally to the component.
c) CSS modules must be defined inline.
d) CSS modules only work in functional components.
51
c) Fetching data from APIs
d) Creating reusable CSS modules
(55 to 64) Match the correct answer from column A what suits column B
No Column (A) No. Column (B) Answer
1 Class Component A Immutable data passed from
parent to child.
2 State B A React hook used to manage
state in functional components.
52
3 Prop Drilling C A method used to update state in
class components.
4 ReactDOM.render() D Optimizes functional
components to avoid
unnecessary re-renders.
5 Functional Component E Renders a React component into
the DOM.
6 React.memo F A more complex component
using ES6 class syntax.
7 Props G A way to scope styles to a
particular component.
8 setState H Passing data through many
components to reach a deeply
nested one.
9 CSS Modules I A simple JavaScript function
that returns a React element.
10 useState J Data specific to a component
that can change over time.
53
Lesson 4
Name Hooks
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
1. Define what Hooks are in React.
2. Recall the rules of using Hooks in React.
➢ Understanding
1. Explain the purpose of useState, useReducer,
useContext, and useEffect Hooks.
2. Describe how Hooks manage state and side effects in
functional components.
➢ Applying
1. Use useState to manage state in functional components.
2. Implement state management using useReducer for
complex state logic.
3. Utilize useContext to share state across components
without prop drilling.
4. Apply useEffect to handle component lifecycle events
like mounting, updating, and unmounting.
➢ Analyzing
1. Compare useState and useReducer for managing
component state.
2. Analyze how useEffect manages side effects in response
to state changes.
➢ Evaluating
1. Assess the benefits and limitations of using Hooks
versus class components for state management.
2. Evaluate the impact of using useContext for state
sharing on component structure and reusability.
3. Determine when to use useState versus useReducer
based on the complexity of state logic.
➢ Creating
1. Create functional components using various Hooks
(useState, useReducer, useContext, useEffect).
54
2. Implement a state-sharing mechanism using useContext
in a component tree.
3. Build a component that uses useEffect to handle
asynchronous data fetching or timers.
Code Description
TPK20 writing asynchronous code using various
Knowledge techniques
TPK21 Basic routing and calling a controller method
from a route
Code Description
Skill
TPC5.4 Using UI Framework (React)
TPC5.7 Using controllers and routes for APIs and URLs
55
Lesson Four: Hooks
56
Section 1 Introduction to Hooks
1-1 Introduction to Hooks
In React version 16.8, "Hooks" are introduced as tools that simplify
working with React, particularly when avoiding class components. They
enable special functions in functional components to manage state, handle
side effects, and more. React provides built-in Hooks like useState and
useEffect, and you can create custom Hooks. Hooks facilitate easy sharing
between components, allowing for code simplicity and flexibility without
requiring a complete code overhaul. They also encourage code modularity
by breaking it down into specific functions and enhance initial state
management through reducers.
57
2-2 State in React
The UI that is generated in a React app is a function of the state. To invoke
reactivity in an app, all we need to do is modify the state, and the React
library will take care of the rest. The graphic below sums up the
relationship between the application UX, state, and props in React:
58
3-1 The useState Hook
The useState Hook is the most basic API provided by React to interact with
state. To better understand how this hook works, let’s look at a counter app
example. First, let’s create the state:
const [count, setCount] = useState(0);
The above piece of code creates a state variable called count and a function
called setCount that can be used to update the state. The initial value of the
state is set to 0. Now, we’ll update the state by incrementing the value of
count by 1:
setCount(count + 1);
Finally, we’ll use the state:
<p>You clicked {count} times</p>
In this example, we used the state by displaying the value of count in the
UI.
59
3-2 The useReducer Hook
The useReducer Hook allows us to manage state by dispatching actions and
then responding to them in the reducer function. Again, we’ll use a counter
app example to understand how this hook works:
const [state, dispatch] = useReducer(reducerFunc, 0);
We call the useReducer Hook with the reducer function and the initial state
as arguments. It returns the current state and a dispatch function. Whenever
we need to update the state, we can call the dispatch function with an action
object:
dispatch({ type: 'INCREMENT' })
React then calls the reducer function with the action object. Here’s what a
common reducer function looks like:
function reducerFunc(state, action) {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
case 'RESET':
return 0;
case 'SET':
return action.val;
}
}
At the end of this transaction, whatever the reducer function returns become
the new state and is accessible through the state variable. Here’s a sketch
that explains the flow of data in the useReducer Hook:
60
3-3 State management with the useContext Hook
Next, let’s look at how the useContext Hook comes into the picture for state
management. The general idea is to store a piece of data that components
can use, but the pattern and the use cases are different.
While useState and useReducer are used to manage the state that is scoped
to a component, useContext is used to manage state that is shared across
components. Its main purpose is to avoid prop drilling when a piece of state
is supposed to be accessed by a child component several levels down the
component tree. One of the primary use cases of context is to manage the
theme of the application. So, let’s look at the code for the same.
Inside a component near the top of the component tree, we’ll create the
context:
export const themeContext = createContext('light');
Notice how the newly created context object is exported from here. To use
that context, we’ll import it in a component down the tree:
import { useContext } from 'react';
import { ThemeContext } from './App.js';
61
export default function Button({ children }) {
const theme = useContext(ThemeContext);
// ...
}
But, for the above code to work, we need to first wrap the component tree
above this consumer component with the context Provider:
<ThemeContext.Provider value={theme}>
{children}
</ThemeContext.Provider>
With that in place, the consumer component will receive the value supplied
by the Provider. Whenever the value supplied to the Provider is updated,
the child below will be able to access that latest updated value.
63
useEffect*/
},[state1,state2])
3. useEffect with state variables in dependency array and cleanup
useEffect(() => {
/*the code you want to run on every render has to be in here, the dependency
array with state means that the code will run everytime this component mounts as
well as when these state variables change and the value will be captured by the
useEffect*/
/*cleanup is used to remove any unwanted loops, intervals, listeners when the
component unmounts*/
return () => console.log("clean up");
},[state1,state2])
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
let timer = setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
64
return <h1>I've rendered {count} times!</h1>;
}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<Timer />);
Terminology:
• Hooks: Functions that let you use state and other features in
functional components.
• useState: Adds state to functional components.
• useReducer: Manages complex state with a reducer function.
• useContext: Shares data across components without prop drilling.
• useEffect: Handles side effects like data fetching after rendering.
65
Dear Learner: Answer the following questions.
Dear learner: Put "True" in front of the correct statement and "False" in front
of the incorrect statement.
66
73 React Router allows you to navigate between different
components without refreshing the page.
74 The createBrowserRouter function is used to configure
routing in a React application.
67
77 Where should Hooks be called within a component?
A. Inside loops
B. Inside nested functions
C. At the top level of functional components
D. In the return statement of components
68
D. useMemo
69
84 How do you capture a dynamic URL parameter using
React Router?
A. useEffect
B. useParams
C. useState
D. useDispatch
70
Lesson 5
Name Manage App Location with React Router
Goals / By the end of this lesson, students should be able to:
Outcomes ➢ Remembering
3. Define client-side routing and server-side rendering.
4. Identify the main features of React Router.
➢ Understanding
4. Explain how React Router manages app location and
routing in single-page applications.
5. Describe the differences between server-side rendering
(SSR) and client-side rendering (CSR).
➢ Applying
7. Implement basic routing in a React application using
React Router.
8. Create navigation using Link components from react-
router-dom.
9. Use dynamic routes and URL parameters with
useParams.
10.Integrate server-side rendering (SSR) into a React
application.
➢ Analyzing
5. Analyze the benefits of client-side routing for a faster
user experience.
6. Compare SSR and CSR in terms of performance and
SEO friendliness.
➢ Evaluating
4. Assess the impact of using React Router on the
structure and behavior of a single-page application.
5. Evaluate the advantages and disadvantages of SSR and
CSR in different use cases.
➢ Creating
5. Develop a single-page application with multiple routes
using React Router.
71
6. Implement a navigation bar that uses Link components
to navigate between different routes.
7. Set up dynamic routing to handle URL parameters and
render specific components based on the URL.
Code Description
TPK21 Basic routing and calling a controller method
Knowledge from a route
TPK22 Analyze and solve common web applications
tasks by writing PHP programs
Code Description
TPC5.4 Using UI Framework (React)
Skill
TPC5.5 Creating an authentication system for your
application
TPC5.7 Using controllers and routes for APIs and URLs
72
Lesson Five: Manage App Location with React Router
73
Section 1 Introduction to Routing
1-1 Introduction
Client-side routing is one of the most important features to make use of
while developing single-page web applications. In web development,
routing describes the process by which a user clicks a link on a webpage
and is directed to a new page with different content and a unique URL. In
server-side routing, this would require making a request to the server and
navigating to a new HTML document. For single-page applications,
however, client-side routing can allow an app to update a URL and display
a new UI without making a server request for a new document. As you can
imagine, this leads to a faster, more streamlined user experience.
75
);
}
Route Configuration in React Router v6
1. BrowserRouter Wrapper:
The BrowserRouter component is used to wrap the entire application,
enabling routing functionality. It ensures that the routes work as
expected across the app.
2. Routes and Route Components:
Routing is defined using a Routes component, which acts as a
container for all Route components. Each Route defines a specific
path and the corresponding component to render.
3. Base Route (/):
The base route (path="/") renders the ProductList component when
the user visits the root URL. This serves as the home page.
4. Dynamic Route (/product/:id):
The path="/product/:id" route is a dynamic route where :id acts as a
URL parameter. When a user visits a URL like /product/123, the
ProductDetails component is rendered, and the id value can be
accessed using the useParams hook.
5. Wildcard Route (*):
The path="*" is a fallback route that matches any undefined paths. It
renders the NotFound component, which is typically used to display a
404 error page.
Creating a NavBar
In our new NavBar component, we import the Link hook from react-router-
dom. To attach each Link to a URL path, we use the “to” prop, similar to
how the anchor element, <a> uses the href attribute in HTML.
import { Link } from "react-router-dom";
function NavBar() {
76
return (
// Match the route to the Link with the "to" prop
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/login">Login</Link>
);
}
export default NavBar
Navigation Links:
The <Link> component is used for navigation between routes without
refreshing the page. For example:
<Link to="/">Home</Link> navigates to the home page.
<Link to="/product/123">Product Details</Link> navigates to a specific
product.
77
function ProductDetails() {
const { id } = useParams();
return (
<>
<h1>{id}</h1>
</>
);
}
export default ProductDetails;
const { id } = useParams(); :
• The useParams hook extracts the id parameter from the URL. In the
context of your previous Link, this id corresponds to the product.id
passed in the URL.
• If the URL is /product/5, the id variable will be set to 5.
Section 3 ReactJS server-side rendering vs client-side rendering SSR
(Server-Side Rendering), CSR (Client-Side Rendering).
For a given website / web-application, you can use react either client-side,
server-side or both.
3-1 Client-Side
78
Over here, you are completely running ReactJS on the browser. This is the
simplest setup and includes most examples (including the ones on
http://reactjs.org). The initial HTML rendered by the server is a placeholder
and the entire UI is rendered in the browser once all your scripts load.
3-2 Server-Side
79
Think of ReactJS as a server-side templating engine here (like jade,
handlebars, etc...). The HTML rendered by the server contains the UI as it
should be, and you do not wait for any scripts to load. Your page can be
indexed by a search engine (if one does not execute any JavaScript).
Since the UI is rendered on the server, none of your event handlers would
work and there's no interactivity (you have a static page).
80
Terminology:
• Client-Side Routing: Navigating between pages in a single-page app
without reloading.
• React Router: Library for defining routes and navigation in React
apps.
• Server-Side Rendering (SSR): Server renders initial HTML for
faster load and better SEO.
• Client-Side Rendering (CSR): Browser renders app, slower initial
load but smoother interactions.
81
Dear learner: Complete the question.
82
(92 to 101) Match the correct answer from column A what suits column B
No Column (A) No. Column (B) Answer
1 useState hook A Shares state between
components
2 useReducer hook B Creates navigational links
3 useContext hook C Manages local component state
4 useEffect hook D Renders the routes
5 useParams hook E Handles side effects
6 createBrowserRouter F Handles complex state logic
7 RouterProvider G Configures routing
8 React Router H Placeholder for child
components
9 Link component I Enables client-side routing
10 Outlet component J Extracts URL parameters
83
Terminology:
• React.js (ReactJS): A JavaScript library by Facebook for building
UIs in single-page apps using reusable components.
• Virtual DOM: An in-memory version of the DOM used by ReactJS
to optimize rendering by updating only changed elements.
• JSX (JavaScript XML): A syntax for writing HTML-like code in
JavaScript files, transformed into standard JavaScript before running.
• React Native: A framework for building mobile apps for iOS,
Android, and Windows using native components.
• React Components: Reusable building blocks of a React app, acting
like custom HTML elements.
• Functional Components: Simple JavaScript functions that return
React elements. Ideal for static UI elements.
• Class Components: More complex components using ES6 classes.
They manage their own state and show inheritance.
• Props: Immutable data passed from parent to child components, used
to render dynamic content.
• State: Data specific to a component that can change and affect
rendering.
• State Management: Managing and updating state across
components.
• Props: Immutable data passed from parent to child components.
• Prop Drilling: Passing data through many components to reach a
deeply nested one.
• Context API: Centralizes data management, avoiding prop drilling.
• Hooks: Functions that let you use state and other features in
functional components.
• useState: Adds state to functional components.
• useReducer: Manages complex state with a reducer function.
• useContext: Shares data across components without prop drilling.
• useEffect: Handles side effects like data fetching after rendering.
• Client-Side Routing: Navigating between pages in a single-page app
without reloading.
84
• React Router: Library for defining routes and navigation in React
apps.
• Server-Side Rendering (SSR): Server renders initial HTML for
faster load and better SEO.
• Client-Side Rendering (CSR): Browser renders app, slower initial
load but smoother interactions.
85
Attention, students! Just a quick reminder: answers
don't just fall from the sky. Sometimes you've got to dig in and find them yourself. Think of it
as a treasure hunt, but with more brainpower and fewer pirate hats! Happy hunting!
No Answer
1 False
2 True
3 False
4 True
5 False
6 True
7 False
8 True
9 C
10 B
11 A
12 C
13 C
14 B
15 C
16 B
17 Single-page
18 Virtual
19 JavaScript
20 Curly braces {}
LESSON 2
21 Differences
22 Component-based
23 JSX
24 React Native
25 React.js is an open-source JavaScript library. It differs from
other frameworks by focusing the use of a Virtual DOM for
efficient UI rendering.
86
26 JSX is a syntax extension for JavaScript that allows developers
to write HTML-like code within JavaScript files.
27 React Native is used for building mobile applications, while
ReactJS is used for web applications .
28 Components are reusable pieces of code that define parts of the UI,
making the development of complex applications easier and more
modular.
29 True
30 False
31 True
32 False
33 True
34 False
35 True
36 True
37 True
38 False
39 C
40 B
LESSON 3
41 B
42 B
43 C
44 B
45 B
46 A
47 A
48 Parent, child.
49 Useeffect()
50 Style
51 setState()
52 re-render.
53 immutable.
54 Redux,Context
55 7
87
56 10
57 8
58 6
59 4
60 1
61 9
62 3
63 5
64 2
LESSON 4
65 Managing and updating state across components.
66 Managing and updating state across components.
67 False
68 False
69 False
70 True
71 False
72 True
73 True
74 True
75 B
76 C
77 C
78 B
79 C
80 B
81 C
82 B
83 B
84 B
LESSON 5
85 SPA
86 Unmounts
87 useReducer
88 useParams
88
89 React-router-dom
90 Routes
91 Path
92 3
93 9
94 1
95 7
96 4
97 2
98 6
99 10
100 8
101 5
89