SlideShare ist ein Scribd-Unternehmen logo
1 von 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/

Weitere ähnliche Inhalte

Was ist angesagt?

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
 

Was ist angesagt? (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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Mehr von BOSC Tech Labs

How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdfHow to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdfBOSC Tech Labs
 
How to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfHow to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfBOSC 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
 

Mehr von BOSC Tech Labs (20)

How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdfHow to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
How to Create Custom Animations in Flutter – A Step-by-Step Guide.pdf
 
How to create components in ReactJS_.pdf
How to create components in ReactJS_.pdfHow to create components in ReactJS_.pdf
How to create components in ReactJS_.pdf
 
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
 

Kürzlich hochgeladen

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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
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
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
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
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 

Kürzlich hochgeladen (20)

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
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.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)
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
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...
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
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
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 

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/