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

Unit 4_ Routing and State Management

Unit 4 covers React Router and state management in React applications, detailing how to manage routing, create single-page applications, and handle state using local and global contexts. It introduces Redux for state management, explaining its architecture, including stores, actions, and reducers, as well as how to connect React with Redux. Additionally, it discusses React Hooks, specifically useState and useEffect, for managing state and side effects in functional components.

Uploaded by

Akash Kale
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)
8 views

Unit 4_ Routing and State Management

Unit 4 covers React Router and state management in React applications, detailing how to manage routing, create single-page applications, and handle state using local and global contexts. It introduces Redux for state management, explaining its architecture, including stores, actions, and reducers, as well as how to connect React with Redux. Additionally, it discusses React Hooks, specifically useState and useEffect, for managing state and side effects in functional components.

Uploaded by

Akash Kale
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/ 28

Unit 4: Routing and State Management

❖ Introduction to React Router

● React Router is a JavaScript package that helps manage a React


application's URL and state.
● React Router is a JavaScript framework that lets us handle client
and server-side routing in React applications.
● It enables the creation of single-page web or mobile apps that
allow navigating without refreshing the page.
● It also allows us to use browser history features while preserving
the right application view.
● React Router is a library for handling routing and navigation in
React JS Applications.

❖ History of Router

● The history in React Router is an object that allows React Router to


subscribe to changes in the URL and manipulate the browser history
stack.
● It also provides APIs for these actions.
● React-Router is a popular React library that is heavily used for
client-side routing and offers single-page routing.
● It provides various Component APIs( like Route, Link, Switch, etc.) that
you can use in your React application to render different components
based on the URL path names on a single page.

❖ Single Page Application Overview

● React Router is a routing library that helps with navigation between


pages in a Single Page Application.

● Steps to Build a React Single Page App


● Step 1: Set Up Your Development Environment. ...
● Step 2: Structure Your React Project. ...
● Step 3: Create Components. ...
● Step 4: Add Routing. ...
● Step 5: Style Your Application. ...
● Step 6: Fetch Data from an API. ...
● Step 7: Deploy Your React SPA.

❖ configure React Router

To configure React Router in React.js, you can follow these steps:

● Install React Router: Run npm install react-router-dom in your project terminal.
● Wrap your application: In the src folder, open the index.js file and import
BrowserRouter from react-router-dom. Then, wrap the root component in
BrowserRouter.
● Define routes: Use the Route component to define your routes. For example, to define
three routes, you can use the following code:

Code

<Route exact path="/" component={Home} />

<Route path="/about" component={About} />

<Route path="/contact" component={Contact} />

​ Navigate between routes



​ Use the Link component to navigate between routes. For example, to create a navigation
menu, you can use the following code:



​ Code
​ <nav>
​ <ul>
​ <li><Link to="/">Home</Link></li>
​ <li><Link to="/about">About</Link></li>
​ <li><Link to="/contact">Contact</Link></li>
​ </ul>
​ </nav>

❖ Load the router library

To load the React Router library in ReactJS, you can install it using the following
steps:

● Open a new terminal


● Run npm install react-router-dom or yarn add react-router-dom
● Wait for the installation to complete

Once the library is installed, you can make it available in your app by:

● Opening the index.js file in the src folder


● Importing BrowserRouter from react-router-dom
● Wrapping the root component (the App component) in BrowserRouter

Here are some other things you can do with React Router:

● Define routes: Use the BrowserRouter, Route, and Switch components to define the
routes you want to handle
● Create components: Create separate components for each route or page
● Navigate: Use the Link component to navigate between routes
● Handle route parameters: Use the :paramName syntax to specify a dynamic route path
● Access route parameters: Use the useParams hook to access parameters in the
component

❖ Navigating between Routes
● To navigate between routes, you can use the Link component from
react-router-dom. This component renders an anchor tag (<a>) that allows
users to click and navigate to the specified route.
● Example

import React from 'react';

import { Link } from 'react-router-dom';

function Navigation() {

return (

<nav>

<ul><li><Link to="/">Home</Link></li>

<li><Link to="/about">About</Link></li>

<li><Link to="/contact">Contact</Link></li></ul>

</nav>

);

export default Navigation;

❖ Route Parameters and Nested Routes


● Route Parameters are used to query any content in the component
directly from URL.
● Route Parameters are used to transport data across requests.
● Route Parameters are used in the place of query strings
Syntax:

http://localhost:3200/product?id=1&name=tv

http://localhost:3200/1/tv

● Parameters are configured in <Route>

Syntax:

● <Route path=”/product/:param1/:param2”> </Route>


● Parameters are passed into URL

Syntax:

● http://localhost:3200/product/param1val/param2val
● To access the route parameters you can use the method “useParams()”

Example

import React from 'react';

import { useParams } from 'react-router-dom';

function UserProfile() {

const { username } = useParams();

return <div>User Profile: {username}</div>;

export default UserProfile;


❖ Nested Routes
● Nested Routes in React are used to create multi level navigation.
● It allows us to build complex layouts rendering components at different levels.
● It is done with the help of Outlet component provided by react router dom.

Syntax:

<Route path="parent" element ={<Parent />}>

<Route path="child" element = {<Child/>}/>

</Route >

const Parent = ()=>{

return(<Outlet />)

❖ Dynamic Routing
● Dynamic routing is a routing method used in web development where the
routes of an application are determined dynamically.
● Dynamic routing is a powerful technique used in web development to handle
navigation and rendering of pages based on changing parameters.
● Unlike traditional static routing, where pages are created and rendered
component by component, dynamic routing allows for more flexible and
efficient handling of complex app scenarios.
● Route is used to specify which component will be rendered at a particular
path or url, path is provided using "path" attribute.
❖ Nesting Routes
● Nested routes enables you to have multiple components render on the same
page with route parity.
● Nested Routes are a type of routing in which one route is linked to another
route.
● To set up routing on the client side in the React project and to enable
navigation in our project, we will use the React Router library.
● React Router is a powerful library that helps in creating single-page
applications (SPAs).
● Nested routes are one of React’s unique features that allow users to swap
out specific view fragments based on the current path.

❖ Invalid URL
● A bad URL or an invalid URL is a URL that contains symbols, spaces, or structures that
Google cannot process.
● These characters and structures include spaces, backslashes, and relative URLs like
“/contact. html” instead of the complete URL, such as “https://site.com/contact.html.”

❖ Handle Conditional statement in JSX


● A component can render specified content in UI. - It is defined by using
“render()” method.
● In various situations a component must able to render different types of
contents.
● You can design component with conditional rendering, so that it can
render content according to state and situation.
● It requires the traditional JavaScript operator like “if, switch, ternary
etc.”

function LoginSuccess(props){

return <h2>Login Success..</h2>


}

function LoginFailure(props){

return <h2>Login Failed..</h2>

class MainContent extends React.Component

constructor(props){

super(props);

this.state = {

statusmsg: false,

content: ''

this.LoginClick = this.LoginClick.bind(this);

LoginClick(e){

if(e.target[0].value=='john' &&

e.target[1].value=='admin')

this.setState({

content: <LoginSuccess />


})

} else {

this.setState({

content: <LoginFailure />

})}}

render(){

return (

<>

<h3>User Login</h3>

<form onSubmit={this.LoginClick} >

<dl>

<dt>User Name</dt>

<dd><input type="text"/></dd>

<dt>Password</dt>

<dd><input type="password"/></dd>

</dl>

<button>Login</button></form> <div> {this.state.content} </div>


</> )}}

ReactDOM.render(

<MainContent />,

document.getElementById('root')
);

State Management

❖ Local State vs. Global State


● Local state: The state according to what's on the local device.
● Global state: The state which has been received from other devices.
● Global state is the state that is shared across multiple components and affects
their behavior or appearance.

❖ State Lift-Up
● "lifting state up" is a technique that allows multiple components to share and
update the same state.
● This is done by moving the state management from the child components to
a common ancestor component, usually the parent component.
● The parent component then passes the state down to the child components as
props.
● Lifting state up is a pattern in React where you move the state from a
lower-level component to a higher-level component, so that it can be shared
between multiple child components.

❖ Context API for Global State


● React's Global Context allows you to share data across the components
of an application without the need to pass the data through props at
each level, using global context states you can access information from
anywhere in your application regardless of whether the component is a
direct child of the one that holds that.
● The biggest use of the Context API is to create a global context within
your entire React. js application. The store is now the most delicate
piece of data in our application, and it is susceptible to bad usage, i.e.
one bad change and the whole application will crash.

Redux
❖ Introduction to Redux
● React-Redux is the official Redux binding for React.
● It allows React components to read data from a Redux store and dispatch
actions to update the store.
● Essentially, React-Redux provides a way to manage and share the
application's state across multiple components in a React application.
● Redux is an open-source JavaScript library used to manage application state.
● React uses Redux for building the user interface.
● It was first introduced by Dan Abramov and Andrew Clark in 2015.
● React Redux is the official React binding for Redux. It allows React components to read data
from a Redux Store, and dispatch Actions to the Store to update data. Redux helps apps to
scale by providing a sensible way to manage state through a unidirectional data flow model.
React Redux is conceptually simple. It subscribes to the Redux store, checks to see if the data
which your component wants have changed, and re-renders your component.

Redux was inspired by Flux. Redux studied the Flux architecture and omitted unnecessary
complexity.

○ Redux does not have Dispatcher concept.


○ Redux has an only Store whereas Flux has many Stores.
○ The Action objects will be received and handled directly by Store.

❖ Redux Architecture

The components of Redux architecture are explained below.


STORE: A Store is a place where the entire state of your application lists. It manages the status of
the application and has a dispatch(action) function. It is like a brain responsible for all moving parts
in Redux.

ACTION: Action is sent or dispatched from the view which are payloads that can be read by
Reducers. It is a pure object created to store the information of the user's event. It includes
information such as type of action, time of occurrence, location of occurrence, its coordinates, and
which state it aims to change.

REDUCER: Reducer read the payloads from the actions and then updates the store via the state
accordingly. It is a pure function to return a new state from the initial state.

❖ Provider Component
● The Provider component in React is a tool that allows developers to share data
between a parent component and its child components.
● A Provider is a higher order component provided to us by the Context
object. We can create a Context object, using the createContext method
that React provides for us. The Provider receives a value prop, which
contains the data that we want to pass down.

❖ Dispatchers
● dispatch is a fundamental concept that plays a crucial role in managing
state changes in your application. Dispatch is a function that sends an
action to the Redux store, which then triggers a state change in your
application.
● In Redux, dispatch needs to tell the app that the state has been updated.
❖ View Controllers
● A function that returns a React element and provides the ability to attach events and value
into the component. This simplifies integrating with external controlled components with
non-standard prop names.
● A view controller manages a single root view, which may itself contain any number of
subviews. User interactions with that view hierarchy are handled by your view controller,
which coordinates with other objects of your app as needed. Every app has at least one
view controller whose content fills the main window.

❖ Connecting React with Redux

1. Install NodeJS. …
2. Install ReactJS and create an application. …
3. Installing Redux and Redux Toolkit. …
4. Setting up the Redux Store and Reducers. …
5. Connect Redux with React Component. …
6. Run Your Application. …
7. Final Output.

To connect a React application with Redux, you can follow these steps:

● Install libraries: Install the Redux and React-Redux libraries


● Create a store: Create a Redux store
● Wrap the main app component: Wrap the main app component with the
Provider component
● Pass the store into the React component: Pass the store into the React
component

Here's an example of how to connect a React component with the Redux store:
● Import the necessary modules, including React, createRoot, Provider, Redux
store, and the main App component
● Locate the HTML element with the "root" ID
● Create a rendering instance using createRoot
● Display the entire application in the "root" HTML element

The Provider component connects the React component to the Redux store, giving
all child components access to its state.

The connect() function in the React Redux package connects the React component
to the Redux store. The connect() function returns a wrapper function that takes a
component and returns a wrapper component with additional props.

❖Hooks:
❖ Introduction to Hooks
● React Hooks are functions that allow developers to use React features and
state management in a React component without writing a class.
● React Hooks are like special tools that make it easier to add features to your
function components, without the need for complex class components.
● Hooks are functions that let you “hook into” React state and lifecycle
features from function components.
● React Hook Form is one such library that helps to manage complex forms.

❖ useState hook
● It allows React developers to update, handle and manipulate state inside
functional components without converting into class component.
● 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.

Import useState
To use the useState Hook, we first need to import it into our component.

import { useState } from "react";

Notice that we are destructuring useState from react as it is a named export.

Initialize useState
We initialize our state by calling useState in our function component.

useState accepts an initial state and returns two values:

● The current state.


● A function that updates the state.

import { useState } from "react";

function FavoriteColor() {

const [color, setColor] = useState("");

Notice that again, we are destructuring the returned values from useState.

The first value, color, is our current state.

The second value, setColor, is the function that is used to update our state.
Syntax:

function App() {

const [name, setName] = useState(‘John’);

OnButtonClick = () => setName(‘David’);

return <div>{name} </div>

❖ useEffect hook

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.

useEffect(<function>, <dependency>)

import { useState, useEffect } from "react";

import ReactDOM from "react-dom/client";

function Timer() {

const [count, setCount] = useState(0);

useEffect(() => {

setTimeout(() => {

setCount((count) => count + 1);}, 1000);});

return <h1>I've rendered {count} times!</h1>;}


const root = ReactDOM.createRoot(document.getElementById('root'));

root.render(<Timer />);

● React useEffect hook handles the effects of the dependency array.

● The useEffect Hook allows us to perform side effects on the components.

● Fetching data, directly updating the DOM and timers are some side effects. It is

called every time any state if the dependency array is modified or updated.

❖ Custom Hook
● Hooks are reusable functions.
● When you have component logic that needs to be used by multiple
components, we can extract that logic to a custom Hook.
● Custom Hooks start with "use". Example: useFetch.
● Creating a custom hook is the same as creating a JavaScript function whose
name starts with “use”.
● Custom Hooks in React are a powerful feature that allows us to extract
component logic into reusable functions.
● These Hooks are JavaScript functions that can use other Hooks provided by
React. They enable us to organize logic into separate, reusable modules.
● Example

import React , {useState ,useEffect} from "react";

function FirstComponent(props){

const [counter , setCounter] = useState(initializer);

function resetCounter(){
setCounter(counter + 1):

useEffect(() => {

console.log(counter);

} , [counter]);

const clickedButton = resetCounter;

return (

<div>

<h1> This is the First Component</h1>

<button onClick={clickedButton}>

Click here!

</button>

</div>

);

export default FirstComponent;

❖ useRef hook
● The useRef Hook allows you to persist values between renders.

● It can be used to store a mutable value that does not cause a

re-render when updated.

● It can be used to access a DOM element directly.

● useRef() only returns one item. It returns an Object called current.

● When we initialize useRef we set the initial value: useRef(0).

● The useRef hook allows you to persist values between renders without
triggering a re-render.

● Whether you’re dealing with DOM manipulation, storing previous


values, or managing timers, useRef is an efficient solution.

Example

import React, { useRef } from 'react';

function MyComponent() {

const inputRef = useRef(null);

const focusInput = () => {

inputRef.current.focus();

};

return (

<div>

<input ref={inputRef} type="text" />

<button onClick={focusInput}>Focus Input</button>


</div>

);

❖ useMemo hook
● The React useMemo Hook returns a memoized value.
● The useMemo Hook only runs when one of its dependencies update.
● The useMemo Hook can be used to keep expensive, resource intensive
functions from needlessly running.
● useMemo hook is used to get the memoized value of a function in react
components.
● It works on the concept of memoization which refers to caching the output
of a function for a given argument to save the computation time. Hence, it
improves the application performance.
● The useMemo Hook returns a memoized value and prevents the
application from unnecessary re-renders. It is useful in heavy
computations and processes when using functional components. The
useMemo hook helps optimize performance by memoizing expensive
calculations.
● Example

import React, { useState } from "react";

function App() {

const [number, setNumber] = useState(0);


const squaredNum = squareNum(number);

const [counter, setCounter] = useState(0);

const onChangeHandler = (e) => {

setNumber(e.target.value);

};

const counterHander = () => {

setCounter(counter + 1);

};

return (

<div className="App">

<h1>Welcome to Geeksforgeeks</h1>

<input type="number" placeholder="Enter a number" value={number}


onChange={onChangeHandler} ></input>

<div>OUTPUT: {squaredNum}</div>

<button onClick={counterHander}>

Counter ++

</button>
<div>Counter : {counter}</div>

</div>

);}

function squareNum(number) {

console.log("Squaring will be done!");

return Math.pow(number, 2);

export default App;

❖useContext hook
● Context provides a way to pass data or state through the component tree
without having to pass props down manually through each nested
component.
● It is designed to share data that can be considered as global data for a tree of
React components, such as the current authenticated user or theme(e.g.
color, paddings, margins, font-sizes).
● UseContext is a React Hook that lets you read and subscribe to context
from your component.
● const value = useContext(SomeContext)
● The useContext hook is a part of React's hooks API introduced in React 16.8.
● It allows components to consume state or context without the need for prop drilling,
which can lead to cleaner and more maintainable code.
● Example

import { createContext, useContext } from 'react';

const ThemeContext = createContext(null);

export default function MyApp() {

return (

<ThemeContext.Provider value="dark">

<Form />

</ThemeContext.Provider>)}

function Form() {

return (

<Panel title="Welcome">

<Button>Sign up</Button>

<Button>Log in</Button>

</Panel> );}

function Panel({ title, children }) {

const theme = useContext(ThemeContext);

const className = 'panel-' + theme;

return (

<section className={className}>

<h1>{title}</h1>
{children}

</section>)}

function Button({ children }) {

const theme = useContext(ThemeContext);

const className = 'button-' + theme;

return (

<button className={className}>

{children}

</button> );}

❖ useReducer hook
● The useReducer hook takes three arguments including reducer, initial state,
and the function to load the initial state lazily.
● Syntax: const [state, dispatch] = useReducer(reducer, initialArgs, init);

Parameters

● reducer: The reducer function that specifies how the state gets updated. It
must be pure, should take the state and action as arguments, and should
return the next state. State and action can be of any types.
● initialArg: The value from which the initial state is calculated. It can be a
value of any type. How the initial state is calculated from it depends on the
next init argument.
● optional init: The initializer function that should return the initial state. If it’s
not specified, the initial state is set to initialArg. Otherwise, the initial state is
set to the result of calling init(initialArg).
● useReducer returns an array with exactly two values:
● The current state. During the first render, it’s set to init(initialArg) or
initialArg (if there’s no init).
● The dispatch function that lets you update the state to a different value and
trigger a re-render.
● Example

import { useReducer } from 'react';

function reducer(state, action) {

if (action.type === 'incremented_age') {

return {

age: state.age + 1

};

throw Error('Unknown action.');

export default function Counter() {


const [state, dispatch] = useReducer(reducer, { age: 42 });

return (

<>

<button onClick={() => {

dispatch({ type: 'incremented_age' })

}}>

Increment age

</button>

<p>Hello! You are {state.age}.</p>

</>

);

You might also like