Unit 4_ Routing and State Management
Unit 4_ Routing and State Management
❖ History of Router
● 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
To load the React Router library in ReactJS, you can install it using the following
steps:
Once the library is installed, you can make it available in your app by:
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
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>
);
http://localhost:3200/product?id=1&name=tv
http://localhost:3200/1/tv
Syntax:
Syntax:
● http://localhost:3200/product/param1val/param2val
● To access the route parameters you can use the method “useParams()”
Example
function UserProfile() {
Syntax:
</Route >
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.”
function LoginSuccess(props){
function LoginFailure(props){
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({
} else {
this.setState({
})}}
render(){
return (
<>
<h3>User Login</h3>
<dl>
<dt>User Name</dt>
<dd><input type="text"/></dd>
<dt>Password</dt>
<dd><input type="password"/></dd>
</dl>
ReactDOM.render(
<MainContent />,
document.getElementById('root')
);
State Management
❖ 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.
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 Architecture
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.
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:
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.
Initialize useState
We initialize our state by calling useState in our function component.
function FavoriteColor() {
Notice that again, we are destructuring the returned values from useState.
The second value, setColor, is the function that is used to update our state.
Syntax:
function App() {
❖ 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(<function>, <dependency>)
function Timer() {
useEffect(() => {
setTimeout(() => {
root.render(<Timer />);
● 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
function FirstComponent(props){
function resetCounter(){
setCounter(counter + 1):
useEffect(() => {
console.log(counter);
} , [counter]);
return (
<div>
<button onClick={clickedButton}>
Click here!
</button>
</div>
);
❖ useRef hook
● The useRef Hook allows you to persist values between renders.
● The useRef hook allows you to persist values between renders without
triggering a re-render.
Example
function MyComponent() {
inputRef.current.focus();
};
return (
<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
function App() {
setNumber(e.target.value);
};
setCounter(counter + 1);
};
return (
<div className="App">
<h1>Welcome to Geeksforgeeks</h1>
<div>OUTPUT: {squaredNum}</div>
<button onClick={counterHander}>
Counter ++
</button>
<div>Counter : {counter}</div>
</div>
);}
function squareNum(number) {
❖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
return (
<ThemeContext.Provider value="dark">
<Form />
</ThemeContext.Provider>)}
function Form() {
return (
<Panel title="Welcome">
<Button>Sign up</Button>
<Button>Log in</Button>
</Panel> );}
return (
<section className={className}>
<h1>{title}</h1>
{children}
</section>)}
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
return {
age: state.age + 1
};
return (
<>
}}>
Increment age
</button>
</>
);