1724083844-Chapter 5 - ReactJS Advance Guide
1724083844-Chapter 5 - ReactJS Advance Guide
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.
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
Source: https://blog.openreplay.com/images/understanding-the-useref-hook/images/hero.png
Classroom Activity
Features of useRef
Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity
Implement a Counter which Increment and Decrement the counts using useReducer
Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity
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:
Source: https://atomizedobjects.com/blog/react/what-is-usereducer-in-react/
Classroom Activity
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
• 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?
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?
Answer: a
Code splitting and lazy loading
Quiz
4. In Redux, what is the role of a reducer?
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!