React
M.Jeevan Babu
Assistant Professor
Department of CSE
VVIT,Guntur 1
React Routing
• React Router is a standard library for creating
dynamic routes and navigation in React JS
Applications.
• It allows you to manage navigation in your app
by defining routes that connect the URL paths
to specific components.
• With React Router, you can implement different
views for different parts of your application
without the need for a full-page refresh.
2
• This is a key feature of single-page applications
(SPAs), where only the necessary content is
updated as the user navigates.
• The current latest verstion is React router
dom v6.
3
Features of React Router
• Declarative Routing: React Router v6 uses
the Routes and Route components to define
routes declaratively, making the routing
configuration simple and easy to read.
• Nested Routes: It supports nested routes,
allowing for complex and hierarchical routing
structures, which helps in organizing the
application better.
4
• ProgrammaticNavigation
The useNavigate hook enables programmatic
navigation, allowing developers to navigate
between routes based on certain conditions or
user actions.
5
• Route Parameters: It provides dynamic
routing with route parameters, enabling the
creation of routes that can match multiple URL
patterns.
6
Components of React Router
• BrowserRouter
– Uses the HTML5 history API to keep your UI in
sync with the URL
– Example
<BrowserRouter>
(/* Your routes go here */)
</BrowserRouter>
7
• Routes and Route
-Routes: A container for all your route
definitions.
-Route: Defines a single route with a path and
the component to render.
8
Example
-<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
9
Link and NavLink
• Link: Creates navigational links in your
application.
• NavLink: Similar to Link but provides
additional styling attributes when the link is
active.
10
Example
<nav>
<NavLink to="/"
activeClassName="active">Home</NavLink>
<Link to="/about">About</Link>
</nav>
11
Steps to Create Routes using React Router
• Step 1: Initialize React Project
• Create React application using the following
command.
• npx create-react-app react-router-example
• cd react-router-example
• Step 2: Install React Router
• Install react-router in your application write
the following command in your terminal
• npm install react-router-dom@6 12
React Hooks
• React Hooks are used to hook into the
features like state and lifecycle methods of
React Component
• Generally, Hooks are special
functions that provide access to state in
the React Application.
• Hooks were introduced in the 16.8 version of
React.
13
• Hooks give access to states for functional
components while creating a React
application.
• It allows you to use state and other React
features without writing a class.
14
When to use
• With React Hooks, you can add state and
other features directly to a functional
component.
• Hooks like useState and useEffect enable you
to manage state, side effects, and other logic
within your existing functional components,
making your code more concise and avoiding
the need to rewrite components as classes.
15
Hook Rules
• There are 3 rules for hooks:
1. Hooks can only be called inside React
function components.
2. Hooks can only be called at the top level of a
component.
3. Hooks cannot be conditional
16
Types of Hooks
• State Hooks
• Effect Hooks
• Context Hooks
• Ref Hooks
• Callback Hooks
• Reducer
• useMemo
17
State Hook
• It is useSate hook
• The React useState Hook allows us to track
state in a function component
• State generally refers to data or properties
that need to be tracking in an application.
• o use the useState Hook, we first need
to import it into our component.
– Import {useState} from ‘recact’;
18
Intialize useSate
• We initialize our state by calling useState in
our function component.
• seState accepts an initial state and returns two
values:
1. The current state.
2. A function that updates the state.
Example:
function FavoriteColor()
{ const [color, setColor] = useState(“red"); }
19
Read State
• We can now include our state anywhere in our
component by suing { }.
• Example:
– <h1>My favorite color is {color}!</h1>
20
Update state
• To update our state, we use our state updater
function.
• Example:
– <button type="button" onClick={() =>
setColor("blue")} >Blue</button>
21
useEffect Hooks
• The useEffect Hook allows you to perform side
effects in your components.
• Some examples of side effects are: fetching
data, directly updating the DOM, and timers.
• useEffect accepts two arguments. The second
argument is optional.
• Syntax:useEffect(<function>, <dependency>)
22
• useEffect runs on every render. That means
that when the count changes, a render
happens, which then triggers another effect.
• We should always include the second
parameter which accepts an array. We can
optionally pass dependencies to useEffect in
this array
23
No dependency passed:
useEffect(() =>
{
//Runs on every render
});
24
An empty array as dependency:
useEffect(() =>
{
//Runs only on the first render
}, []);
25
Props or state values:
useEffect(() => {
//Runs on the first render
//And any time any dependency value changes },
[prop, state]);
26
• useEffect(() => {
// Side effect logic goes here
return () => {
// Cleanup logic (optional)
};
}, [dependencies]);
27
• Effect function: This is where your side effect
code runs.
• Cleanup function: This optional return
function cleans up side effects like
subscriptions or timers when the component
unmounts.
• Dependencies array: React re-runs the effect
if any of the values in this array change.
28
useRef
• Used to get input from user and assigned the
value to variable or state.
• with the help of useSate if u do that
whenever value changes ,entire component
will be re-rendered.
• useRef doesn’t notify you,when it content
changes.means that updating the value
doesn’t cause component re-render.
29
• You can autofocus an input field by using
useRef.
• You can store previous state values.
30
useMemo
• Used to improve overall performance of the
application
• It will not call for every re-render
• It will during the first render and runs
whenever dependency value changes.
• useEffect will run after the rendering where as
useMemo will run during the rendering.
31
• The useMemo Hook returns a memoized
value and prevents the application from
unnecessary re-renders.
• Syntax:
const a = useMemo (functionThatReturnsValue,
arrayDependencies )
32
useReducer
• Used to store local values to local const
variable.
• The useReducer Hook is the better alternative
to the useState hook and is generally more
preferred over the useState hook when you
have complex state-building logic or when the
next state value depends upon its previous
value or when the components are needed to
be optimized.
33
• The useReducer hook takes two arguments
including reducer, initial state.
• Syntax:
const [state, dispatch] = useReducer(reducer,
initialValue);
34
Event Handlig
• React Events are user interactions with the
web application, such as clicks, keyboard
input, and other actions that trigger a
response in the user interface. Just like HTML
DOM, React also acts upon the events.
• React events are the actions due to user
interaction or system events
35
Event Declaration in React
• <button onClick={handleClick}>
Click Me!
</button>
36
Commonly Used React Event Handlers
• onClickThis event is used to detect mouse
click in the user interface.
• onChangeThis event is used to detect a
change in input field in the user interface.
• onSubmitThis event fires on submission of a
form in the user interface and is also used to
prevent the default behavior of the form.
37
• onKeyDownThis event occurs when user
press any key from keyboard.
• onKeyUpThis event occurs when user
releases any key from keyboard.
• onMouseEnterThis event occours when
mouse enters the boundary of the element
38
Adding React Events
• React events syntax is in camelCase, not
lowercase
• If we need to set events in our code, we have
to pass them, just like props or attributes, to
JSX or HTML.
• We have to pass a function regarding the
process we want to do on fire of this event.
39
React Events Syntax:
• onClick={function}
40
Passing Arguments in React Events
• In React Events, we pass arguments with the
help of arrow functions.
• Like functions, we create parenthesis and pass
arguments, but here it is not possible; we have
to use an arrow function to pass arguments.
41
React Events Arguments Syntax:
• onClick={()=>{function(argument)}}
42
React Event Object
• React Events handlers have an object called
Events, which contains all the details about
the event, like type, value, target, ID, etc.
• So we can pass that event as an argument and
use that event object in our function.
43
React Event Object Syntax:
• onClick={(event)=>{function(event)}}
44
Error Handling
• Handling errors in React is crucial for creating
robust and user-friendly applications.
• React provides several mechanisms to manage
errors effectively. Here are some common
approaches:
1. Error Boundaries
2. try-catch in Event Handlers
45
Error Boundaries
• Error boundaries are a feature in React that
allows components to catch JavaScript errors
anywhere in their component tree and log
those errors, display a fallback UI, or take
other actions.
• To create an error boundary, a component
needs to
define static getDerivedStateFromError and co
mponentDidCatch lifecycle methods.
46
try-catch in Event Handlers
• When dealing with asynchronous operations,
such as fetching data or handling events, you
can use the standard JavaScript try-catch block
to catch errors and handle them gracefully.
47
• async function fetchData() {
try {
const response = await
fetch('https://api.example.com/data');
const data = await response.json();
// Process data
} catch (error) {
console.error('Error fetching data:', error);
// Handle the error
}
}
48
React lifecycle
• React Lifecycle is defined as the series of
methods that are invoked in different stages of
the component’s existence.
49
• Mounting Phase: This phase begins when a
component is created and inserted into the
DOM.
• Updating Phase: This occurs when a
component is re-rendered due to changes in
props or state.
• Unmounting Phase: This is the final phase
when a component is removed from the DOM.
50
51
Mounting
• Mounting means putting elements into the DOM.
• React has four built-in methods that gets called, in
this order, when mounting a component:
1. constructor()
2. getDerivedStateFromProps()
3. render()
4. componentDidMount()
• The render() method is required and will always be
called, the others are optional and will be called if
you define them.
52
constructor
• The constructor() method is called before anything
else, when the component is initiated, and it is the
natural place to set up the initial state and other
initial values.
• The constructor() method is called with the props,
as arguments, and you should always start by
calling the super(props) before anything else, this
will initiate the parent's constructor method and
allows the component to inherit methods from its
parent (React.Component).
53
example
• ..\constructor.txt
54
getDerivedStateFromProps
• The getDerivedStateFromProps() method is
called right before rendering the element(s) in
the DOM.
• This is the natural place to set the state object
based on the initial props.
• It takes state as an argument, and returns an
object with changes to the state.
• Used for updating the state based on props.
Executed before every render.
55
• ..\getDerivedStateFromProps.txt
56
render
• The render() method is required, and is the
method that actually outputs the HTML to the
DOM.
• ..\render.txt
57
componentDidMount()
• The componentDidMount() method is called
after the component is rendered.
• This is where you run statements that requires
that the component is already placed in the
DOM.
• ..\componentdidmount.txt
58
Updating
• The next phase in the lifecycle is when a component
is updated.
• A component is updated whenever there is a change in the
component's state or props.
• React has five built-in methods that gets called, in this order,
when a component is updated:
1. getDerivedStateFromProps()
2. shouldComponentUpdate()
3. render()
4. getSnapshotBeforeUpdate()
5. componentDidUpdate()
• The render() method is required and will always be called,
the others are optional and will be called if you define
them. 59
getDerivedStateFromProps
• getDerivedStateFromProps(props, state) is a static
method that is called just before render() method in
both mounting and updating phase in React.
• ..\updategetDerivedStateFromProps.txt
60
shouldComponentUpdate
• In the shouldComponentUpdate() method you
can return a Boolean value that specifies
whether React should continue with the
rendering or not.
• The default value is true
• ..\shouldcomponentgetupdate.txt
61
render
• The render() method is of course called when
a component gets updated, it has to re-render
the HTML to the DOM, with the new changes.
• ..\updaterender.txt
62
getSnapshotBeforeUpdate
• In the getSnapshotBeforeUpdate() method
you have access to
the props and state before the update,
meaning that even after the update, you can
check what the values were before the update.
• If the getSnapshotBeforeUpdate() method is
present, you should also include
the componentDidUpdate() method,
otherwise you will get an error.
63
..\getSnapshotbeforeUpdate.txt
• When the component is mounting it is rendered with
the favorite color "red".
• When the component has been mounted, a timer
changes the state, and after one second, the favorite
color becomes "yellow".
• This action triggers the update phase, and since this
component has a getSnapshotBeforeUpdate() method,
this method is executed, and writes a message to the
empty DIV1 element.
• Then the componentDidUpdate() method is executed
and writes a message in the empty DIV2 element:
64
componentDidUpdate
• The componentDidUpdate method is called after the
component is updated in the DOM.
• ..\Componentdidupdate.txt
• When the component is mounting it is rendered with the
favorite color "red".
• When the component has been mounted, a timer changes
the state, and the color becomes "yellow".
• This action triggers the update phase, and since this
component has a componentDidUpdate method, this
method is executed and writes a message in the empty DIV
element: 65
Unmounting
• This is the final phase of the lifecycle of the
component which is the phase of unmounting
the component from the DOM. The following
function is the sole member of this phase.
• It has only one built –in function
1. componentWillUnmount()
66
componentWillUnmount()
• This function is invoked before the component
is finally unmounted from the DOM i.e. this
function gets invoked once before the
component is removed from the page and this
denotes the end of the lifecycle.
• ..\unmounting.txt
67