SlideShare a Scribd company logo
1 of 19
React: How To Utilize Context API With Class And
Functional Components:
• Well, React official documentation says Contexts provide a way
to route data through the component tree without having to
manually propagate props at each level.
• Think about a scenario in which several separate components at
various degrees of nested levels need to access the same data. Data
must be sent as props to the component tree when using React so
that any component that requires it may access it.
• Parent components can send data to nested child components in this
way. They use many layers of components to transfer data from one
piece to another.
• Props drilling is a challenge when data must be routed across
numerous features because specific parts get the braces and then
pass them on to their child components as props.
Level 1 – Parent Component (App.js):
import React, { Component } from "react";
import ReactDOM from "react-dom";
import UserProfile from "./UserProfile.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: ""
};
}
render() {
return (
); } } constrootElement = document.getElementById(“root”); ReactDOM.render(, rootElement);
Level – 2 UserProfile.js
import React from "react";
import CurrentUserProfile from "./CurrentUserProfile.js";
constUserProfile = props => {
return (
); }; export default UserProfile;
Level – 3 CurrentUserProfile.js
import React from "react";
constCurrentUserProfile = props => {
return (
{props.currentUser}
); }; export default CurrentUserProfile;
• The nested components in the preceding example have three layers.
The nested element is receiving currentUser information as a prop.
The CurrentUserProfile component receives data from the UserProfile
component via props.
• The UserProfile component does not use the props data in its way.
After three layers of nesting components, examine the situation
where many merely pass the props to their children. In extensive
applications, this may be a significant problem.
• This is where the React Context API comes into play. Context makes it
possible to communicate values like these without passing a prop up
and down the component hierarchy. For a tree of React components,
context offers data that may be deemed globally accessible without
explicitly supplying data to each inner part.
• The previous example may readily be converted to Context-based.
The present component does not require a complete overhaul. Only a
few replacement parts are needed (provider and consumer).
Step-1: Initialize the Context
We are developing a framework in which suppliers and consumers may
thrive.
constContextObject = React.createContext(defaultValue)
createContext() method is used to create a context. You can also
pass the default value to the context variable by passing it to the
createContext().
UserContext.js:
import React from "react";
constUserContext = React.createContext({});
export default UserContext;
This Context object’s current value will be retrieved by React when it
displays a component that subscribes to this Context object. When a
provider cannot be found in the tree, the default value of context is
used.
Step – 2: Create the Provider:
• Two Provider and Consumer Components are created when we create
context. We can develop Provider and Consumer components, export
them, and let other members utilize them as needed.
• This is what UserContext.js would look like after constructing Provider
and Consumer import React from “react”;
• Creating context gives us two Provider and Consumer Components.
We can create Provider and Consumer components and export them
so that they are available for the other components to use them.
No matter at what level this context is used, the Provider must be
wrapped around the parent component. Using the Provider, I’ll
encapsulate App.js and send userCurrent to the down tree.
// this is the equivalent to the createStore method of Redux
constUserContext = React.createContext();
// creating Provider and Consumer and exporting them
export constUserProvider = UserContext.Provider
export constUserConsumer = UserContext.Consumer
export default UserContext;
App.js:
import React, { Component } from "react";
import ReactDOM from "react-dom";
import UserProfile from "./UserProfile.js";
import { UserProvider } from "./UserContext.js";
class App extends Component {
constructor(props) {
super(props);
this.state = {
currentUser: {
name: "Mr.Willey",
address: "USA",
mobile: "+1 (850) 780-1313"
}
};
}
render() {
return (
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(, rootElement);
• The nested child receives the currentUser information from the
parent. We’re getting our information about current users from the
state.
• We can get API information about a user and then pass it on to the
child components that utilize that information. Wrapping userprofile
in a provider imported from UserContext.js is what we’re doing.
• The currentUser object may be accessed by any nested part. When
the provider’s value changes, any consumers nested in it must re-
render.
Step – 3: Create the Consumer:
• In UserContext.js, we’ve already written code to consume it.
Wrapping the child component in the Consumer for Class component
and using the useContext method of React to access context
information is the most straightforward approach to get access to the
context. We can then use props to get at the context value sent in
earlier in the process.
Using the prior illustration as a guide:
(without using context one),
UserProfile.js:
import React from "react";
import CurrentUserProfile from "./CurrentUserProfile.js";
constUserProfile = props => {
return ( ); };
export default UserProfile;
CurrentUserProfile.js:
import React, { useContext } from “react”;
//importing UserContext from UserContext.js file
import { UserContext } from “./UserContext.js”;
constCurrentUserProfile = () => { const user = useContext(UserContext);
return (
{user.name}
{user.address}
{user.mobile}
);
}
}
)};
export default CurrentUserProfile;
(access the Context value.)
Getting data from component A to component Z by passing it to
multiple layers of components. As Data has to be passed through
multiple components, this problem is called Props drilling. Because
some components only just get the props and pass them to the child
component as props. Below is an example of the above scenario.
Image Source: toptal.com
Conclusion:
This is how to utilize react context API with class and functional
components. Professional react js development services offered
by Bosc Tech are helpful to know how to use react context API with
functional and class components. Hope, this will help.
Content Resource: https://bosctechlabs.com/react-utilize-context-api-
with-class-and-functional-components/

More Related Content

What's hot

Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITnamespaceit
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JSBinary Studio
 
Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSRemo Jansen
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?BOSC Tech Labs
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners Varun Raj
 
Having Fun Building Web Applications (Day 2 slides)
Having Fun Building Web Applications (Day 2 slides)Having Fun Building Web Applications (Day 2 slides)
Having Fun Building Web Applications (Day 2 slides)Clarence Ngoh
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation洪 鹏发
 
React js programming concept
React js programming conceptReact js programming concept
React js programming conceptTariqul islam
 
The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!Baharika Sopori
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
React: High level overview for backend developers
React: High level overview for backend developersReact: High level overview for backend developers
React: High level overview for backend developersBonnie DiPasquale
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React NativeEric Deng
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In MeteorDesignveloper
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Katy Slemon
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming PrinciplesAndrii Lundiak
 

What's hot (20)

Introduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace ITIntroduction to React JS for beginners | Namespace IT
Introduction to React JS for beginners | Namespace IT
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Dependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJSDependency Inversion in large-scale TypeScript applications with InversifyJS
Dependency Inversion in large-scale TypeScript applications with InversifyJS
 
What are the components in React?
What are the components in React?What are the components in React?
What are the components in React?
 
Introduction to React JS for beginners
Introduction to React JS for beginners Introduction to React JS for beginners
Introduction to React JS for beginners
 
Having Fun Building Web Applications (Day 2 slides)
Having Fun Building Web Applications (Day 2 slides)Having Fun Building Web Applications (Day 2 slides)
Having Fun Building Web Applications (Day 2 slides)
 
[Final] ReactJS presentation
[Final] ReactJS presentation[Final] ReactJS presentation
[Final] ReactJS presentation
 
React js programming concept
React js programming conceptReact js programming concept
React js programming concept
 
The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!The Benefits of Using React JS for Web Development!
The Benefits of Using React JS for Web Development!
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
React: High level overview for backend developers
React: High level overview for backend developersReact: High level overview for backend developers
React: High level overview for backend developers
 
React context
React context  React context
React context
 
20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native20180518 QNAP Seminar - Introduction to React Native
20180518 QNAP Seminar - Introduction to React Native
 
React – Structure Container Component In Meteor
 React – Structure Container Component In Meteor React – Structure Container Component In Meteor
React – Structure Container Component In Meteor
 
Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...Redux and context api with react native app introduction, use cases, implemen...
Redux and context api with react native app introduction, use cases, implemen...
 
Learn Drupal 8 Render Pipeline
Learn Drupal 8 Render PipelineLearn Drupal 8 Render Pipeline
Learn Drupal 8 Render Pipeline
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
React JS & Functional Programming Principles
React JS & Functional Programming PrinciplesReact JS & Functional Programming Principles
React JS & Functional Programming Principles
 
Its time to React.js
Its time to React.jsIts time to React.js
Its time to React.js
 

Similar to How To Utilize Context API With Class And Functional Componen in React.pptx

React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxBOSC Tech Labs
 
what is context API and How it works in React.pptx
what is context API and How it works in React.pptxwhat is context API and How it works in React.pptx
what is context API and How it works in React.pptxBOSC Tech Labs
 
How to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxHow to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxBOSC Tech Labs
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...Karmanjay Verma
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react jsBOSC Tech Labs
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit TestingEswara Kumar Palakollu
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥Remo Jansen
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfStephieJohn
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react jsdhanushkacnd
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptxsaikatsamanta49
 

Similar to How To Utilize Context API With Class And Functional Componen in React.pptx (20)

React Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptxReact Hooks Best Practices in 2022.pptx
React Hooks Best Practices in 2022.pptx
 
what is context API and How it works in React.pptx
what is context API and How it works in React.pptxwhat is context API and How it works in React.pptx
what is context API and How it works in React.pptx
 
Intro react js
Intro react jsIntro react js
Intro react js
 
How to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptxHow to use UseContext Hook in React.pptx
How to use UseContext Hook in React.pptx
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...React JS; all concepts. Contains React Features, JSX, functional & Class comp...
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
 
How to create components in react js
How to create components in react jsHow to create components in react js
How to create components in react js
 
Reactjs
Reactjs Reactjs
Reactjs
 
ReactJS.pptx
ReactJS.pptxReactJS.pptx
ReactJS.pptx
 
React and Flux life cycle with JSX, React Router and Jest Unit Testing
React and  Flux life cycle with JSX, React Router and Jest Unit TestingReact and  Flux life cycle with JSX, React Router and Jest Unit Testing
React and Flux life cycle with JSX, React Router and Jest Unit Testing
 
reactJS
reactJSreactJS
reactJS
 
Simple React Todo List
Simple React Todo ListSimple React Todo List
Simple React Todo List
 
ReactJs
ReactJsReactJs
ReactJs
 
React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥React + Redux + TypeScript === ♥
React + Redux + TypeScript === ♥
 
react-slides.pptx
react-slides.pptxreact-slides.pptx
react-slides.pptx
 
Fundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdfFundamental Concepts of React JS for Beginners.pdf
Fundamental Concepts of React JS for Beginners.pdf
 
Build web apps with react js
Build web apps with react jsBuild web apps with react js
Build web apps with react js
 
class based component.pptx
class based component.pptxclass based component.pptx
class based component.pptx
 
React JS .NET
React JS .NETReact JS .NET
React JS .NET
 
react-slides.pdf
react-slides.pdfreact-slides.pdf
react-slides.pdf
 

More from BOSC Tech Labs

Guide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfGuide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfBOSC Tech Labs
 
How do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfHow do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfBOSC Tech Labs
 
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfGuide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfBOSC Tech Labs
 
How to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfHow to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfBOSC Tech Labs
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfBOSC Tech Labs
 
How to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfHow to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfBOSC Tech Labs
 
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfSwiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfBOSC Tech Labs
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdfBOSC Tech Labs
 
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...BOSC Tech Labs
 
The Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfThe Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfBOSC Tech Labs
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentBOSC Tech Labs
 
2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & BenefitsBOSC Tech Labs
 
What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?BOSC Tech Labs
 
Top 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsTop 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsBOSC Tech Labs
 
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...BOSC Tech Labs
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSBOSC Tech Labs
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperBOSC Tech Labs
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTBOSC Tech Labs
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfBOSC Tech Labs
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...BOSC Tech Labs
 

More from BOSC Tech Labs (20)

Guide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdfGuide 101_ Material Design in Android App Development.pdf
Guide 101_ Material Design in Android App Development.pdf
 
How do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdfHow do you hire a skilled Android developer for your project_.pdf
How do you hire a skilled Android developer for your project_.pdf
 
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdfGuide to 2024’s Elite Software Developers by MobileAppDaily.pdf
Guide to 2024’s Elite Software Developers by MobileAppDaily.pdf
 
How to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdfHow to build a live chat widget in React_.pdf
How to build a live chat widget in React_.pdf
 
React Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdfReact Best Practices All Developers Should Follow in 2024.pdf
React Best Practices All Developers Should Follow in 2024.pdf
 
How to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdfHow to hire ios app development experts for your next project_.pdf
How to hire ios app development experts for your next project_.pdf
 
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdfSwiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
Swiftui Vs Uikit_ Choosing the Right Ui Framework for ios Apps.pdf
 
3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf3 Ways to Get Started with a React App in 2024.pdf
3 Ways to Get Started with a React App in 2024.pdf
 
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
The iOS Advantage_ How Apple’s Ecosystem Is Setting the Stage for Next-Gen Bu...
 
The Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdfThe Role iOS App Development_ Hiring for the Future.pdf
The Role iOS App Development_ Hiring for the Future.pdf
 
React 19: Revolutionizing Web Development
React 19: Revolutionizing Web DevelopmentReact 19: Revolutionizing Web Development
React 19: Revolutionizing Web Development
 
2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits2024 Custom Software Development Guide: Trends, Steps & Benefits
2024 Custom Software Development Guide: Trends, Steps & Benefits
 
What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?What is the Easiest Way to Hire a React Developer?
What is the Easiest Way to Hire a React Developer?
 
Top 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage TrendsTop 10 React Carousel Component Libraries and their Usage Trends
Top 10 React Carousel Component Libraries and their Usage Trends
 
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
The Comprehensive Tech Guide to iOS Mobile App Development: From Concept to L...
 
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERSSTEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
STEP BY STEP GUIDE TO HIRING EXPERIENCED FLUTTER DEVELOPERS
 
Top 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React DeveloperTop 10 Essential Traits to Look For Hire Remote React Developer
Top 10 Essential Traits to Look For Hire Remote React Developer
 
Transform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPTTransform Your Mobile App Development with ChatGPT
Transform Your Mobile App Development with ChatGPT
 
Which Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdfWhich Is The Best AI Tool For Mobile App Development_.pdf
Which Is The Best AI Tool For Mobile App Development_.pdf
 
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
Revealing Development Efficiency: How AI Powers Innovation in Software Creati...
 

Recently uploaded

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataBradBedford3
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - InfographicHr365.us smith
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 

Recently uploaded (20)

Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer DataAdobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
Adobe Marketo Engage Deep Dives: Using Webhooks to Transfer Data
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
Asset Management Software - Infographic
Asset Management Software - InfographicAsset Management Software - Infographic
Asset Management Software - Infographic
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 

How To Utilize Context API With Class And Functional Componen in React.pptx

  • 1.
  • 2. React: How To Utilize Context API With Class And Functional Components: • Well, React official documentation says Contexts provide a way to route data through the component tree without having to manually propagate props at each level. • Think about a scenario in which several separate components at various degrees of nested levels need to access the same data. Data must be sent as props to the component tree when using React so that any component that requires it may access it.
  • 3. • Parent components can send data to nested child components in this way. They use many layers of components to transfer data from one piece to another. • Props drilling is a challenge when data must be routed across numerous features because specific parts get the braces and then pass them on to their child components as props.
  • 4. Level 1 – Parent Component (App.js): import React, { Component } from "react"; import ReactDOM from "react-dom"; import UserProfile from "./UserProfile.js"; class App extends Component { constructor(props) { super(props); this.state = { currentUser: "" }; } render() { return ( ); } } constrootElement = document.getElementById(“root”); ReactDOM.render(, rootElement);
  • 5. Level – 2 UserProfile.js import React from "react"; import CurrentUserProfile from "./CurrentUserProfile.js"; constUserProfile = props => { return ( ); }; export default UserProfile;
  • 6. Level – 3 CurrentUserProfile.js import React from "react"; constCurrentUserProfile = props => { return ( {props.currentUser} ); }; export default CurrentUserProfile;
  • 7. • The nested components in the preceding example have three layers. The nested element is receiving currentUser information as a prop. The CurrentUserProfile component receives data from the UserProfile component via props. • The UserProfile component does not use the props data in its way. After three layers of nesting components, examine the situation where many merely pass the props to their children. In extensive applications, this may be a significant problem.
  • 8. • This is where the React Context API comes into play. Context makes it possible to communicate values like these without passing a prop up and down the component hierarchy. For a tree of React components, context offers data that may be deemed globally accessible without explicitly supplying data to each inner part. • The previous example may readily be converted to Context-based. The present component does not require a complete overhaul. Only a few replacement parts are needed (provider and consumer).
  • 9. Step-1: Initialize the Context We are developing a framework in which suppliers and consumers may thrive. constContextObject = React.createContext(defaultValue) createContext() method is used to create a context. You can also pass the default value to the context variable by passing it to the createContext().
  • 10. UserContext.js: import React from "react"; constUserContext = React.createContext({}); export default UserContext; This Context object’s current value will be retrieved by React when it displays a component that subscribes to this Context object. When a provider cannot be found in the tree, the default value of context is used.
  • 11. Step – 2: Create the Provider: • Two Provider and Consumer Components are created when we create context. We can develop Provider and Consumer components, export them, and let other members utilize them as needed. • This is what UserContext.js would look like after constructing Provider and Consumer import React from “react”; • Creating context gives us two Provider and Consumer Components. We can create Provider and Consumer components and export them so that they are available for the other components to use them.
  • 12. No matter at what level this context is used, the Provider must be wrapped around the parent component. Using the Provider, I’ll encapsulate App.js and send userCurrent to the down tree. // this is the equivalent to the createStore method of Redux constUserContext = React.createContext(); // creating Provider and Consumer and exporting them export constUserProvider = UserContext.Provider export constUserConsumer = UserContext.Consumer export default UserContext;
  • 13. App.js: import React, { Component } from "react"; import ReactDOM from "react-dom"; import UserProfile from "./UserProfile.js"; import { UserProvider } from "./UserContext.js"; class App extends Component { constructor(props) { super(props); this.state = { currentUser: { name: "Mr.Willey", address: "USA", mobile: "+1 (850) 780-1313" } }; } render() { return ( ); } } const rootElement = document.getElementById("root"); ReactDOM.render(, rootElement);
  • 14. • The nested child receives the currentUser information from the parent. We’re getting our information about current users from the state. • We can get API information about a user and then pass it on to the child components that utilize that information. Wrapping userprofile in a provider imported from UserContext.js is what we’re doing. • The currentUser object may be accessed by any nested part. When the provider’s value changes, any consumers nested in it must re- render.
  • 15. Step – 3: Create the Consumer: • In UserContext.js, we’ve already written code to consume it. Wrapping the child component in the Consumer for Class component and using the useContext method of React to access context information is the most straightforward approach to get access to the context. We can then use props to get at the context value sent in earlier in the process.
  • 16. Using the prior illustration as a guide: (without using context one), UserProfile.js: import React from "react"; import CurrentUserProfile from "./CurrentUserProfile.js"; constUserProfile = props => { return ( ); }; export default UserProfile;
  • 17. CurrentUserProfile.js: import React, { useContext } from “react”; //importing UserContext from UserContext.js file import { UserContext } from “./UserContext.js”; constCurrentUserProfile = () => { const user = useContext(UserContext); return ( {user.name} {user.address} {user.mobile} ); } } )}; export default CurrentUserProfile; (access the Context value.)
  • 18. Getting data from component A to component Z by passing it to multiple layers of components. As Data has to be passed through multiple components, this problem is called Props drilling. Because some components only just get the props and pass them to the child component as props. Below is an example of the above scenario. Image Source: toptal.com
  • 19. Conclusion: This is how to utilize react context API with class and functional components. Professional react js development services offered by Bosc Tech are helpful to know how to use react context API with functional and class components. Hope, this will help. Content Resource: https://bosctechlabs.com/react-utilize-context-api- with-class-and-functional-components/