0% found this document useful (0 votes)
6 views

1724083844-Chapter 5 - ReactJS Advance Guide

This document provides an advanced guide to ReactJS, focusing on React Hooks such as useEffect, custom hooks, useRef, useReducer, useMemo, and useCallback, as well as page routing using React Router. It discusses the advantages and disadvantages of hooks, their usage scenarios, and the importance of routing in single-page applications. The document also includes classroom activities and quizzes to reinforce learning objectives.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

1724083844-Chapter 5 - ReactJS Advance Guide

This document provides an advanced guide to ReactJS, focusing on React Hooks such as useEffect, custom hooks, useRef, useReducer, useMemo, and useCallback, as well as page routing using React Router. It discusses the advantages and disadvantages of hooks, their usage scenarios, and the importance of routing in single-page applications. The document also includes classroom activities and quizzes to reinforce learning objectives.

Uploaded by

P SANTHIYA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

Chapter: 5

ReactJS Advance
Guide
Learning Objectives
You will learn in this lesson:
• Explore Hooks (useEffect, custom hooks, useRef,
useReducer, useMemo, use callback).
• Page Routing.
React Hooks
Introduction
• React Hooks were introduced in React 16.8 as a way to
use state and other React features without writing a class
component.
• Hooks provide a simpler and more functional approach to
managing state, side effects, and other React features.
Need for Hooks
• When you need to develop a function component, and
after that, if you need to include any state to it, earlier we
do that by transforming it into a class.
• However, now we can do that by utilizing the Hook in the
present function component.
Key Features of React Hooks:
• useState: Adds state to functional components.
• useEffect: Manages side effects like data fetching
and subscriptions.
• useContext: Accesses context values without
nesting.
• useReducer: Manages complex state logic with
reducers.
• useMemo: Memorizes values to optimize
performance.
• useCallback: Memorizes callbacks to optimize
performance.
• useRef: Accesses and interacts with DOM elements
directly.
Advantages of React Hooks:
• Simplicity: Hooks make it easier to understand and
write components by removing the need for classes.
• Code Reusability: Custom hooks allow you to
extract and reuse stateful logic across multiple
components.
• Separation of Concerns: Hooks enable better
separation of concerns by allowing you to split related
logic into different functions.
• Easier to Test: Functions and hooks are generally
easier to test compared to class components.
• Improved Performance: Hooks like useMemo and
useCallback help optimize performance by
memoizing values and functions.
Disadvantages of React Hooks:
• Learning Curve: Hooks introduces a new way of
thinking about state and lifecycle, which can be
challenging for those accustomed to class
components.
• Complexity in Large Components: Overusing
hooks in large components can lead to complexity
and make the code harder to follow.
• Performance Pitfalls: Incorrect use of hooks like
useEffect can lead to performance issues or
unintended side effects.
Understanding useEffect in React
• The useEffect hook in React is a powerful tool that allows you to perform side effects in function
components.
• It is the functional component equivalent of lifecycle methods in class components such as
componentDidMount, componentDidUpdate, and componentWillUnmount.
• Basic Usage;
useEffect takes two arguments
1) a callback function containing the side effect logic.
2) an optional array of dependencies.
Understanding useEffect in React
How it Works
• On Mount: The callback function runs after the initial
render when the component mounts.
• On Update: If dependencies are provided, the
callback function runs again after every render if any
dependency has changed.
• On Unmount: The cleanup function (if returned) runs
before the component unmounts and before the
callback runs again during updates.

Source : https://ankitchaudharyy.medium.com/useeffect-hook-managing-react-lifecycle-methods-137eaec74d3b
Classroom Activity

Demonstrate how to use useEffect to perform a side effect, such as fetching data when
the component mounts.

Solution: GitHub Link


When to Use useEffect:
• Fetching Data:
Scenario: You need to fetch data from an API when a component mounts or when specific state or prop values
change.
Example: Fetching a list of users when a component loads.
• Subscribing to Services:
Scenario: You need to subscribe to a service or set up a connection (e.g., WebSocket, external event
listeners) when a component mounts, and clean up the subscription when the component unmounts.
Example: Subscribing to a WebSocket for real-time updates.
• Updating the DOM:
Scenario: You need to manually interact with the DOM after React has rendered it.
Example: Updating the document title or focusing an input element.
When to Use useEffect:
• Setting up Timers:
Scenario: You need to set up timers or intervals and clear them when the component unmounts.
Example: Updating a counter every second.
• Handling Side Effects Based on State or Props Changes:
Scenario: You need to perform side effects in response to changes in state or props.
Example: Logging the user activity whenever a specific prop changes.
• Cleaning Up Resources:
Scenario: You need to clean up resources to avoid memory leaks, such as removing event listeners or
cancelling subscriptions.
Example: Removing a resize event listener.
Custom Hook in React
• Custom hooks are a powerful way to reuse stateful
logic across multiple components in React.
• They allow you to extract and share logic while
keeping your components clean and focused on
rendering.
• A custom hook in React allows you to encapsulate
reusable logic into a single function, making your
components cleaner and more maintainable.
• Custom hooks let you extract component logic into
reusable functions, which can be shared across
multiple components.

Source : https://th.bing.com/th/id/OIP.YPx3jJcs-L9vRpU9NCfkhQHaEJ?rs=1&pid=ImgDetMain
Creating a Custom Hook
• Define a Function: The custom hook is a function
that uses built-in hooks (useState, useEffect, etc.).
• Prefix with use: By convention, custom hooks are
prefixed with use to indicate that they follow the rules
of hooks.

Source: https://th.bing.com/th/id/OIP.YPx3jJcs-L9vRpU9NCfkhQHaEJ?rs=1&pid=ImgDetMain
Guidelines for Creating React Custom Hooks
• Naming Convention
• Encapsulating Stateful Logic
• Function Nature
• Adherence to React Hook Rules
• Modularity and Code Organization
Classroom Activity

Custom Hook: useFetch


Suppose we have to use this counter in multiple components then we would require a
custom hook that can perform the same function multiple times.

Solution: GitHub Link


Understanding useRef in React
• The useRef hook in React is a powerful and
versatile tool that can be used to directly access
and interact with DOM elements, persist values
between renders without causing re-renders, and
create mutable objects that can hold any value.

Source: https://blog.openreplay.com/images/understanding-the-useref-hook/images/hero.png
Classroom Activity

Demonstrate the use of useRef

Solution: GitHub Link


Advantages of useRef
• Direct DOM Manipulation: Allows direct
interaction with DOM elements without triggering
re-renders.
• Persistent Value: Maintains the same object
throughout the component's lifecycle.
• Performance: Avoids unnecessary re-renders
when updating the ref value.
Disadvantages of useRef
• Imperative Code: Leads to more imperative code,
which can be harder to reason about compared to
declarative code.
• Misuse: Can be misused for state management,
leading to bugs and harder-to-maintain code.

Features of useRef

• Initial Value: Accepts an initial value, which can be


any value (e.g., null, object, number).
• Mutable current Property: The current property can
be read and updated without causing re-renders.
• Persistent Object: The ref object is persistent and
does not change between renders.
Understanding useReducer in React
• The useRef hook in React is a powerful and versatile tool that can be used to directly access and interact with
DOM elements, persist values between renders without causing re-renders, and create mutable objects that
can hold any value.

Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity

Implement a Counter which Increment and Decrement the counts using useReducer

Solution: GitHub Link


Advantages of useReducer
• Complex State Logic: Ideal for managing complex
state logic involving multiple sub-values.
• Predictable State Updates: Ensures state
transitions are predictable and easy to follow.
• Decoupling Logic from Components: State
management logic is decoupled from the component,
making it easier to test and maintain.
Disadvantages of useReducer

• Boilerplate Code: Can introduce more boilerplate


code compared to useState.
• Complexity: Might be overkill for simple state
management needs.
• Learning Curve: Requires understanding of reducers
and actions, which might be complex for beginners.
Features of useReducer

• State Initialization: Accepts an initial state and an optional initializer function.


• Reducer Function: A pure function that determines state changes based on action types.
• Dispatch Function: Allows dispatching of actions to trigger state updates.
Understanding useMemo in React
• The useMemo hook in React is used to memoize the result of a function, optimizing performance by
preventing unnecessary computations.
• It returns a memoized value, which means it only recalculates the value when one of its dependencies
changes.
• This can be particularly useful for expensive calculations that should not run on every render.
• Syntax:

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

• The first argument is a function that computes the value.


• The second argument is an array of dependencies that, when changed, will trigger the function to
recompute the value.

Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity

Implement Expensive Calculator using useMemo

Solution: GitHub Link


Advantages of useMemo
• Performance Optimization: Prevents expensive calculations on every render.
• Efficiency: Helps in optimizing components that rely on heavy computations or complex logic.
• Improved Responsiveness: Reduces lag in UI updates by avoiding unnecessary recalculations.

Disadvantages of useMemo
• Overhead: Introducing useMemo where it is not needed can add unnecessary overhead.
• Complexity: May make the code harder to read and maintain if overused or misused.
• Memory Usage: Memoized values are stored in memory, which can increase memory usage if not
managed properly.
Understanding useCallback in React
• The useCallback hook in React is used to memoize functions, optimizing performance by preventing
unnecessary re-creation of functions on each render.
• This can be particularly useful when passing callbacks to optimized child components that rely on
reference equality to prevent unnecessary renders.
• Syntax:

const memoizedCallback = useCallback(() => {doSomething(a, b);},[a, b]);

• The first argument is the function you want to memoize.


• The second argument is an array of dependencies that, when changed, will
cause the function to be recreated.

Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity

Increment Count and Value of a counter using callBack

Solution: GitHub Link


Advantages of useCallback
• Performance Optimization: Helps prevent unnecessary re-renders by ensuring stable function references.
• Efficiency: Reduces the number of times child components re-render, improving performance.
• Improved Code Readability: Clearly shows the intention of preventing unnecessary function recreations.

Disadvantages of useCallback
• Overhead: Using useCallback unnecessarily can add complexity and slight performance overhead.
• Complexity: Can make the code harder to read and maintain if overused or applied incorrectly.
• Memory Usage: Memorized functions are stored in memory, which can increase memory usage if not
managed properly.
Page Routing
What is Routing?
• Routing in reactJS is the mechanism by
which we navigate through a website or web-
application.
• Routing can be server-side routing or client-
side routing.
React Router
• However, React Router is a part of client-side routing.
• React Routing without any knowledge of it can be manually implemented using useState and JSX for
conditioning.
• But being inefficient for large-scale applications like e-commerce, it still can act as a boilerplate for
understanding routing and act as a base for React JS router for example.
• Server-side routing results in every request being a full-page refresh loading unnecessary and repeated data
every time causing a bad UX and delay in loading.
• With client-side routing, it could be the rendering of a new component where routing is handled internally by
JavaScript.
• The component is rendered only without the server being reloaded.
Basic Routing
React Router API
• Browser Router or React Router API is the most
popular library for routing in react to navigate among
different components in a React Application keeping
the UI in alignment with URL.
• According to react-router official docs, “ React
Router is a fully-featured client and server-side
routing library for React, a JavaScript library
for building user interfaces.”
• There are 3 different packages for React Routing.
1. react-router: ​
2. react-router-native: ​
3. react-router-dom:
Components in React Router
React Router DOM in reactJS is categorized into three primary components :
They are the matchers to navigate clients to and from the correct URL requested for using:
1. Route:
• It is the most basic component that maps location to different react components to render a specific UI
when the path matches the current URL\.​
• It is an alternative to an if-statement logic for saying if want to go to the requested /about the path, the route
is responsible for rendering that specific component matching across the current URL like
2. Switch:
• This component works similarly to the switch statement.
• It cuts down the exhaustive checking of each route path with the current URL instead the switch once gets
the correct route path it returns back from there instead of checking till the last route path is written.
Route Changers
There are three types of navigators or route changes :
1. Link
• It is one of the primary ways to navigate the routes instead of putting it in the address bar you render it on UI
as fully accessible just like anchor <href> tags of HTML with the main difference of anchor tags reload the UI
to navigate, but links do not reload it again.
2. NavLink:
• It is an extended version of Link such that it allows us to see whether the < Link> is active or not.
• This component provides isActive property that can be used with the className attribute.
3. Redirect:
• It is a kind of force navigation that will redirect user to the specific page programmers want if such a route is
yet not present in the application to navigate forward to.
• It is a substitute for 404 error pages depending on the website requirement
Classroom Activity

Implement E-commerce Website using ReactJS which includes Page Routing in


Navbar.
Solution: GitHub Link
When to Use Page Routing in Real Time
● Single Page Applications (SPAs): For applications where the user navigates between different views without
full page reloads.
● Dashboards: For admin panels or dashboards where multiple views (e.g., reports, settings) need to be
accessed.
● E-commerce Websites: Where users navigate between different product categories, details, and carts.
● Content Management Systems (CMS): For websites with structured content that needs to be displayed
across different pages.
● Portfolios: Personal or business portfolios where different sections (e.g., About, Projects, Contact) are
shown.
Summary
Well done! You have completed this course and now
you understand about:
• Explore Hooks (useEffect, custom hooks, useRef,
useReducer, useMemo, use callback).
• Page Routing.
Reference
• https://www.coursera.org/learn/front-end-react

• https://react.dev/learn

• https://stackoverflow.com/questions/tagged/reactjs

• https://www.reddit.com/r/reactjs/?rdt=60337

• https://www.reactiflux.com/
Quiz
1. Which React hook is used to perform side effects
in function components?

a) useState
b) useEffect
c) useReducer
d) useRef

Answer: B. useEffect
The useEffect hook is used to handle side effects in function components. This includes tasks like fetching data,
directly updating the DOM, and setting up subscriptions.
Quiz
2. What is the primary purpose of React Router in a
React application?

a) To manage global state


b) To handle page routing and navigation
c) To optimize performance
d) To split code and lazy load components

Answer: b
To handle page routing and navigation
Quiz
3. Which technique in React is used to improve performance by only
loading parts of the app when needed?

a) Code splitting and lazy loading


b) Using Redux Dev Tools
c) Setting up Redux with React
d) Creating custom hooks

Answer: a
Code splitting and lazy loading
Quiz
4. In Redux, what is the role of a reducer?

a) To send data to the store


b) To update the state based on the action received
c) To dispatch actions
d) To connect React components to the Redux store

Answer: b
To update the state based on the action received
Quiz
5. Which tool can you use to inspect and debug Redux state
changes in a React application?

a) React Router
b) useEffect
c) Redux Dev Tools
d) useMemo

Answer: c
Redux Dev Tools
Thank you!

You might also like