React Context: How to Use the useContext Hook

TECHNOLOGY

We can explicitly define the classes context property with a type annotation to make it strongly-typed: class Header extends React

In React,Guest Posting the components are the building blocks of the product. These components are defined in the tree hierarchy where one component is the parent of the child component.

 

The data flow in react is down the hierarchy i.e. the data flow from parent component to child component and further down. If the component is deep down in the hierarchy from the root component then the data is passed through all the middle components first and then it will be accessible to the component that is deep down the hierarchy.

 

To prevent this type of design some reactjs developers use redux as a library that works on the global store that stores the data or state globally and is accessible to all the components directly without passing data or state down the hierarchy.

 

Context is another very curious and awesome way introduced by react to store the data or state globally. 

 

For implementing react context in your project:

 

1. Create a file to create a context object and export that context object from that file.

 

theme-context.js import React from ‘react’ export const ThemeContext = React.createContext( ‘dark’ );

 

Here we have created and exported a context object. Context object accepts a default parameter or value ( default props ) that can be passed to it. In case if no props are passed by the parent component then it takes default props defined in the context object.

 

A react context object always comes with a provider function. In the next step, we will see what a provider is.

 

2. Now in a parent component whose values are to be passed to child component.  

 

We will wrap any child component that is going down the hierarchy in a react context provider.

Note: If any child component wants to access the state or value from ancestor than the parent or grandparent of that child component should be wrapped inside a react context provider.

 

Component A  —>  Component B  —->   Component C ——> Component D

  (ancestor)     (child 1)     (child 2)         (child 3)

 

Here Component A is the root component, component B is the child of component A, component C is the child of component B, component D is the child of component C.

 

If child 3 wants to access the data from the ancestor or component A than any of component B, C or D should be wrapped in provider.

 

The Child who wants to access the data, its any parent, or itself should be wrapped inside the context provider of the ancestor that pass the data. 

 

app.js import {ThemeContext, themes} from './theme-context'; import ThemedButton from './themed-button'; // An intermediate component that uses the ThemedButton function Toolbar(props) { return ( Change Theme ThemedButton> ); } class App extends React.Component { constructor(props) { super(props); this.state = { theme: themes.light, }; this.toggleTheme = () => { this.setState(state => ({ theme: state.theme === themes.dark ? themes.light : themes.dark, })); }; } render() { // The ThemedButton button inside the ThemeProvider // uses the theme from the state while the one outside uses // the default dark theme return ( Section> Page> ); } } ReactDOM.render(, document.root);

 

Here class App is the ancestor. The Toolbar is a child functional component and ThemedButton is also a child component.

 

The Toolbar is wrapped inside the context provider. The context provider passes the values that can be accessible to Toolbar and its any child component. ThemedButton is not wrapped inside any of the context providers, therefore, it will take the default value of the context.

 

The value passed by the provider to the child component can be accessible by it or any child of that child component.

 

Note: Any child component wrapped inside the provider will take the values passed and if the child component is not wrapped inside the provider it will use the default value of the react context provider.

 

So we are done with parent component, now let’s move on to the child component definition.

 

3. In child components, we can access the values in multiple ways. 

 

Let’s discuss the first way to access the value in child component (contextType).

 

Themed-button.js Before Context import {ThemeContext} from './theme-context'; class ThemedButton extends React.Component { render() { let props = this.props; let theme = this.props; // this.props used return ( ); } } ThemedButton.contextType = ThemeContext; export default ThemedButton; After Context import {ThemeContext} from './theme-context'; import React from ‘react’ class ThemedButton extends React.Component { render() { let props = this.props; let theme = this.context; //Replaced by this.context return ( ); } } ThemedButton.contextType = ThemeContext; export default ThemedButton;

 

Here ThemedButton is the child component. If you want to access the value then make use contextType before exporting the component. After that everywhere you have used this.props can be replaced by this.context.  

 

Another way of accessing values is by using react hooks.

 

import {ThemeContext} from './theme-context'; import React, {useContext} from ‘react’ class ThemedButton extends React.Component { render() { let theme = useContext(ThemeContext); return ( ); } } export default ThemedButton;

 

Here we made use of hooks useContext. After this, we can directly access the properties as shown above.

Be it a software developer, programmer, coder, or a consultant, CronJ has it all. CronJ has been a trustworthy company for startups, small companies, and large enterprises. Hire the web of experienced React developers for your esteemed project today. ReactJS Development Services

 

 Hope you all the understood it

Thank You..!

Source: Free Guest Posting Articles from ArticlesFactory.com

Contact Us

  • India Job Seekers
    3, First Floor, Maruthanayagam Pillai Complex, LIC Colony, KK Nagar, Trichy - 620021
  • +91 97905 55741

Quick Links

Job Categories

Job Categories

jobs near me | amazon jobs | jobs hiring near me | job alert | fast job | work from home jobs | part time jobs near me | government jobs | freelance | civil service jobs | online jobs | free job alert | work from home | apprenticeship | linkedin jobs | sbi careers | remote jobs | google jobs | part time jobs | employment | data entry jobs | google careers | amazon force | hiring near me | job search | data analyst | job vacancy | part time | software engineer | data scientist | jobs hiring | receptionist | freelance jobs | apple home advisor | majhi naukri | railway recruitment | side hustle | virtual assistant jobs | latest govt jobs | monster jobs | administrative assistant | microsoft careers | accenture careers | marriott careers | software developer | online jobs for students | free job | account manager | fast job search | post office recruitment | job bank | amazon jobs near me | apple jobs | deloitte careers | find a job | tesla careers | cashier | job alert | highest paying jobs | apple careers | receptionist jobs near me | job application | vacancies | naukri jobs | amazon work from home | icici careers | all jobs for you | online data entry jobs | full time jobs near me | qatar airways careers | aps jobs | online jobs from home | ibm careers | fci recruitment | emirates careers | sbi recruitment | glassdoor jobs | cvs careers | flight attendant jobs | trade me jobs | infosys careers | tesla jobs | work up job | government job vacancies | amazon delivery jobs | assam rifles recruitment | job seeker | work from home jobs near me | it jobs | job openings near me | govt job alert | wells fargo careers | work abroad | devnetjobsindia | railway recruitment | financial analyst | indigo careers | bsf recruitment | mechanical engineering jobs | data entry jobs from home | best jobs | government jobs | security jobs | online teaching jobs | sbi recruitment | civil engineering jobs | bank of america careers | marketing jobs | post office recruitment | apna job | jop | customer service jobs | wipro careers | upwork jobs | post office recruitment | business development manager | salesforce careers | gov jobs | rbi office attendant | construction jobs | job opportunities | assistant manager | crpf recruitment | pwc careers | customer service representative | hubstaff talent | public jobs | marketing manager | microsoft jobs | onlinedataentryjob | ey careers | transcription jobs | cisf recruitment | operations manager | sales executive | devnetjobs | amazon hiring | amazon delivery driver | remote jobs near me | railway jobs | jobs from home | amazon near me | dream job | airport jobs | amazon fulfillment center | government vacancies | kpmg careers | jp morgan careers | amazon work from home jobs | part time work from home jobs | call center jobs | cyber security jobs | kvs recruitment | mhc recruitment | executive assistant | online work from home | delivery driver jobs | flipkart careers | online jobs work from home | hr jobs | blue collar jobs | online tutoring jobs | amazon application | job sites | babysitting jobs | freelance writing jobs | online job 715 | job search sites | army jobs | cvs jobs | freelancing websites | human resources jobs | great job | barc recruitment | office work | india post recruitment | office jobs near me | ui ux designer | driving jobs near me | graphic design jobs | free alert job | recruitment online | axis bank career | recruitment agencies | transcribe me | digital marketing jobs | data analyst jobs | ibegin tcs | indian post recruitment | cognizant careers | medical assistant jobs | security jobs near me | cabin crew jobs | receptionist jobs | capgemini careers | qa engineer | iocl recruitment | latest job | account executive | computer science jobs | ikea jobs | graduate jobs | hilton careers | dfccil recruitment | online part time jobs | accounting jobs | icici bank career | career explorer | indian railway recruitment | majhi naukri | kormo jobs | babysitting jobs near me | post office vacancy | teaching jobs near me | online work | ppsc jobs | get a job | job centre | spotify careers | railway recruitment | central government jobs | management trainee | gulfwalkin | itbp recruitment | apprenticeships near me | agriculture jobs | brand manager | amazon remote jobs | new job | driving jobs | dfccil recruitment | iocl recruitment | job center | online typing jobs | we work remotely | fiverr jobs | engineering jobs | undp jobs | top jobs | job vacancy near me | construction worker | morgan stanley careers | fci recruitment | spotify jobs | cleaning jobs near me | nursing jobs near me | summer jobs | weworkremotely | cruise ship jobs | delivery jobs near me | cag recruitment | hdfc careers | drdo recruitment | bhel recruitment | part time remote jobs | data entry work from home | psc recruitment | uber careers | amazon flex driver | siemens careers | teaching jobs | finance jobs | security guard jobs | easy typing job | customer success manager | sbi po apply online | network rail jobs | electrical engineering jobs | pepsico careers | construction jobs near me | amazon driver jobs | oracle careers | job websites | pilot jobs | private job | proofreading jobs | project coordinator | system engineer | personal assistant jobs | business development executive | stay at home jobs | hsbc careers | standard bank careers | itbp recruitment | freshersvoice | home office jobs | best paying jobs in finance | ib recruitment | student at work | air force jobs | jobs hiring near me part time | salesforce jobs | amazon jobs from home | ib recruitment | ntpc recruitment | teaching assistant jobs | barc recruitment | twitter careers | remote jobs hiring | medical assistant jobs near me | esic recruitment | ubs careers | business analyst jobs | zoho careers | barclays careers | employment agencies | biotechnology jobs | creative jobs | ongc recruitment | jobsplus | dsssb vacancy | part time jobs for students | data science jobs | ssb recruitment | business administration jobs | world bank jobs | sales assistant | hal recruitment | delivery jobs | bank jobs near me | english teacher | full time jobs | indian coast guard recruitment | student job search | income tax recruitment | linkedin careers | salesforce developer | hotel jobs | administrative assistant jobs | aavin recruitment | naukri gulf | esic recruitment | typing jobs | all jobs | chase careers | maruti suzuki career | aws jobs | system analyst | cisco careers | accenture jobs | citibank careers | drdo recruitment | chemical engineering jobs | hotel jobs near me | vedantu careers | project manager jobs | production manager | new vacancy | good jobs | office assistant | noc canada | psychology jobs | night shift jobs | white collar jobs | online money earning | aai recruitment | canada post jobs | paypal careers | bartending jobs near me | hiresine | navy recruitment | freelance writing | typing jobs from home | post office vacancy | healthcare jobs | job advertisement | defence job | hdfc bank careers | adobe careers | siemens jobs | overnight jobs near me | accor careers | housekeeping jobs | high paying jobs near me | nursing jobs | ksp recruitment | honeywell careers | electrician jobs | cleaning jobs | medical representative | data entry operator | office jobs | mhada recruitment | sales engineer | pepsico jobs | logistics jobs | data entry jobs work from home | vectrus careers | credit suisse careers | arts jobs | bank of america jobs | p&g careers | accounting jobs near me | sales jobs | amazon online jobs | pharmacist jobs | state jobs | ford careers | good paying jobs | home based jobs | application for employment | deloitte jobs | dell careers | real estate jobs | mes recruitment | night jobs near me | call center jobs near me | rpa developer | cashier jobs near me | appen jobs | wells fargo jobs | bel recruitment | computer operator | top job | aai recruitment | mhada recruitment | lic recruitment | infopark jobs | linkingsky | forklift operator | local jobs | sbi clerk apply online | nestle careers | remote work from home jobs | staff nurse vacancy | remote customer service jobs | unilever careers | tcs recruitment | job openings | environmental jobs | amazon employment | enggwave | nabard recruitment | flipkart jobs | creative circle | stackoverflow jobs | factory jobs near me | sap careers | job fairs near me | hckrecruitment | hospital jobs | work from home jobs without investment | writing jobs | ibm jobs | journalism jobs | machine operator | cisco jobs | environmental science jobs | jobs for freshers | hcl careers | airbnb careers | sap jobs | medical transcriptionist | best paying jobs | gis jobs | blackrock careers | part time jobs from home | i need a job | government job vacancy | psu jobs | relationship manager | work from home jobs no experience | software engineer jobs | hr jobs near me | stripe careers | job vacancies | jobassam | bookkeeping jobs | overnight jobs | public relations jobs | ssb recruitment | part time work near me | emirates group careers | sbi recruitment | truck driving jobs | public service commission jobs | igcar recruitment | sbi clerk apply online | admin jobs | olx jobs | manpower jobs | vistara careers | find an apprenticeship | remote data entry jobs | social media jobs | marriott jobs | ikea careers | it jobs near me | npcil recruitment | intel careers | new jobs | research assistant jobs | job offer | kvs vacancy | hospitality jobs | territorial army recruitment | sbi vacancy | amazon hiring near me | job boards | hgv driver jobs | government jobs | aai recruitment | becil recruitment | lionbridge jobs | sales jobs near me | pwc jobs | tamilanguide | career change | it technician | information technology jobs | airline jobs | medical coding jobs | vmware careers | job posting | night shift jobs near me | interior design jobs | etihad careers | job market | unacademy careers | best work from home jobs | indgovtjobs | tata steel career | healthcare administration jobs | cg govt job | student jobs | aviation jobs | microbiology jobs | transcriber | highest paying jobs in the world | data entry jobs near me | hgv jobs | hospital jobs near me | summer jobs near me | myntra careers | bloomberg careers | up police vacancy | computer engineer | forklift jobs | amazon customer service jobs | intel jobs | web developer jobs | jll careers | business intelligence analyst | wfh jobs | psc jobs | railway vacancy | bel recruitment | housekeeping jobs near me | transcriptionist | bmw jobs | nmdc recruitment | job search engines | good work | no experience jobs | railway jobs | psssb recruitment | typist | best paying jobs in basic industries | looking for a job | management jobs | sbi recruitment apply online | administrative officer | startup jobs | government jobs near me | freelance work | job agencies near me | latest govt jobs | us bank careers | forklift jobs near me | nature jobs | trade jobs | good paying jobs near me | train driver jobs | online jobs for students to earn money at home | graduate schemes | deutsche bank careers | part time work from home | work from home jobs for freshers | front desk jobs near me | dubizzle jobs | vacancy | tutoring jobs | admin jobs near me | amazon part time jobs | air force vacancy | paytm careers | senior manager | bank recruitment | npcil recruitment | indian railways recruitment | union jobs | computer technician | today jobs | copywriting jobs | iaf recruitment | delivery driver | oracle jobs | ux researcher | coinbase careers | legal jobs | information security analyst | amazon distribution center | supply chain manager | infosys recruitment | no experience jobs near me | delivery driver jobs near me | cbre careers | tamilan jobs | supply chain management jobs | punjab police jobs | manager jobs near me | category manager | new vacancy | all job for you | mba jobs | green jobs | social worker jobs | market research analyst | twitter jobs | data scientist jobs | online part time jobs for students | lorry driver | workday careers | swiggy careers | iqvia careers | side jobs | at home jobs near me | new job alert | social media manager jobs | zomato careers | registered nurse jobs near me | administration jobs | oil and gas jobs | procurement manager | shine jobs | nmdc recruitment | jobline | electrician jobs near me | amazon job application | free job posting sites | genpact careers | offcampusjobs4u | jobs around me | biomedical engineering jobs | igcar recruitment | security officer | online data entry | nielit recruitment | jobs abroad | iti jobs | gulf jobs | axis bank recruitment | best paying jobs in technology | hdfc bank recruitment | fao jobs | us postal service jobs | best job search engines | nvidia careers | icici bank recruitment | slack careers | whitehat jr jobs | study job line | admin assistant | adp careers | trainee train driver | job hunting | work from home jobs for students | southern railway recruitment | cvs application | online writing jobs | tech mahindra careers | army jobs | it engineer | sap consultant | amazon recruitment | byju's jobs | highest paying jobs without a degree | police jobs | ppsc jobs | safety officer jobs | cg job | online jobs no experience | texco vacancy | nithra jobs | hiring manager | online jobs near me | tcs jobs | engineering manager | data entry clerk | production assistant | public service jobs | assam rifles recruitment | hssc recruitment | jobs | abb careers | income tax department recruitment | local jobs near me | freelance jobs online | nyks recruitment | education jobs | find a job gov | adnoc careers | employment agencies near me | apple work from home | shell careers | quality engineer | hilton jobs | international relations jobs | librarian jobs | india post recruitment | job recruitment | department of health vacancies | career options | kpmg jobs | ntpc recruitment | job search websites | credit analyst | kbr careers | zoom careers | cs jobs | railway recruitment apply online | self employed jobs | intelligence bureau recruitment | nestle jobs | career choices | remote working jobs | sales development representative | people first jobs | medical jobs | analyst jobs | night jobs | vodafone careers | overseas jobs | upsc recruitment | uber jobs | madras high court recruitment | part time work | ncl recruitment | procurement jobs | online jobs hiring | bandhan bank recruitment | social media marketing jobs | communications jobs | aavin recruitment | linkedin job search | offline vacancy | chemistry jobs | qatar careers | software developer jobs | pharmacist jobs near me | mechanic jobs near me | mastercard careers | financial analyst jobs | medical transcription jobs | visa careers | amazon apply | job applications near me | aws careers | medical receptionist jobs | supply chain jobs | call center agent | front end developer jobs | staff nurse | coding jobs | easy jobs | intelligence bureau recruitment | public administration jobs | jobs for introverts | tuition teacher | bro recruitment | hotel career | wipro recruitment | marketing jobs near me | construction manager | staff nurse vacancy | jobs near me for freshers | yes bank careers | list of jobs | tamilan guide | ey jobs | remote nursing jobs | marketing specialist | byju's careers | office assistant jobs | govt jobs | freelancing sites | marketing coordinator | fiverr freelance | railroad jobs | office worker | aavin recruitment | oil india limited recruitment | hr specialist | job net | paypal jobs | clerical work | abbott careers | careers near me | digital marketing manager | security guard jobs near me | offshore jobs | canada post careers | side hustle jobs | job agencies | nhpc recruitment | psc vacancies | ongc recruitment | shop assistant | cvs health careers | bp careers | cash jobs near me | accounts payable jobs | kpsc recruitment | railway vacancy | recruitment consultant | amazon flex jobs | marketing assistant | oil india recruitment | intuit careers | remote accounting jobs | qualcomm careers | health career | pharmaceutical sales jobs | airbus careers | virtual jobs | jkssb recruitment | local truck driving jobs | modeling jobs | psc vacancies | delivery manager | executive assistant jobs | kotak mahindra bank career | ossc recruitment | government vacancies | anz careers | border force jobs | computer teacher vacancy | gail recruitment | chef jobs | job postings | idbi bank recruitment | local government jobs | sales coordinator | private bank jobs | oil rig jobs | flipkart job vacancy | first job | caterpillar careers | best jobs in the world | jpmorgan chase careers | kbr jobs | flydubai careers | engineering apprenticeships | maersk careers | air arabia careers | business jobs | science jobs | qa analyst | etihad airways careers | post office recruitment apply online | product manager jobs | senior consultant | mes jobs | ppsc online apply | senior software engineer | teleperformance jobs | cargill careers | hr assistant jobs | hostess jobs near me | sbi recruitment apply online | day labor near me | job apps | health and safety jobs | teacher vacancy | top jobs | all govt jobs | social work jobs near me | computer engineering jobs | indian railways recruitment | operations manager jobs | best part time jobs | best remote jobs | manufacturing jobs | career times | public sector jobs | philips careers | cashier jobs | amazon india careers | front desk receptionist | research jobs | procurement specialist | job hiring | customer service jobs near me | online data entry jobs without investment | online jobs for students to earn money | work near me | amazon delivery driver jobs | full stack engineer | new job vacancy | offline vacancy | hr assistant | axis bank recruitment | concentrix jobs | jobs hiring near me full time | sales clerk | office work near me | tech jobs | side jobs from home | tnstc recruitment | employment opportunities | gov nokri | world bank careers | service delivery manager | best freelance websites | iti jobs beta | chase bank careers | airbnb jobs | low stress jobs | aiims recruitment | clara jobs | air canada careers | new govt jobs | airtel careers | atlassian careers | bus driver jobs | cyber security analyst | computer jobs | bank of baroda recruitment | general motors careers | medical billing and coding jobs | vacancy near me | medical receptionist | kormo | freelance graphic designer | find jobs near me | job shop | workday jobs | pgcil recruitment | logistics manager | stripe jobs | khaleej times jobs | product specialist | digital marketing specialist | concentrix careers | job ideas | workindia job | real estate jobs near me | legal secretary | online english teaching jobs | translator jobs | dice jobs | technician jobs | night auditor | work from home customer service jobs | biology jobs | bnp paribas careers | logistics coordinator | job desk | emaar careers | nlc careers | truck driving jobs near me | amazon glassdoor | reliance careers | merchant navy jobs | fleet manager | digital nomad jobs | security analyst | cvs hiring | jobkind | law jobs | oil india recruitment | bsf recruitment | amazon canada jobs | indian coast guard recruitment | baker hughes careers | resdex naukri | barclays jobs | application engineer | best online jobs | product marketing manager | rpf vacancy | wellsfargo careers | rbi careers | room attendant | rotana careers | project coordinator jobs | al futtaim careers | indian railway jobs | jobs after 12th | ernst and young careers | media jobs | unilever jobs | executive engineer | amazon career day | chef jobs near me | marketing analyst | acting jobs | international jobs | drdo recruitment | ubs jobs | design jobs | traffic control jobs | reed recruiter | amazon recruitment | inova careers | legal assistant jobs | kpsc recruitment | hotel manager | astrazeneca careers | upsc vacancy | department of education jobs | tata motors career | fast jobs | brand ambassador jobs | coal india recruitment | canadian job bank | lorry driver jobs | payroll jobs | factory worker | carpenter work | healthcare management jobs | google work from home | online data entry jobs without investment daily payment | home based work | cag recruitment | kmf recruitment | government jobs after 12th | graphic design jobs near me | top paying jobs | best jobs for introverts | apprenticeship programs | noc engineer | ecil recruitment | industrial engineering jobs | sbi careers | job centre online | online jobs without investment | exxonmobil careers | property management jobs

© 2024 India Job Seekers.