React JS React Hooks Usecontext

In a typical React application, data is passed top-down (parent to child) via props, but this can be cumbersome for certain types of props (e.g. locale preference, UI theme) that are required by many components within an application. Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the tree.

Let's discuss one example. We have one component ParentComponent. ParentComponent have three child component A, B and C.

  • A have no child component.
  • B have B1 child component.
  • C have C1 child component. C1 have C2 childComponent.
    • Now we have one data value which is used in A , B1 and C2. then we have to pass this value to all child component through props. In this case context will help us to resolve this issue.

      1. userContext.js

      userContext.js
      import React from 'react'; const UserContext = React.userContext(); const UserProvider = UserContext.Provider; const UserConsumer = UserContext.Consumer; export { UserProvider, UserConsumer}

      2. ParentComponent.js

      ParentComponent.js
      import React from 'react'; import ComponentC from './ComponentC'; const UserContext = React.createContext(); function ParentComponent { return( <div> <UserContext.Provider value="React"> <ComponentC /> </UserContext.Provider> </div> ); } export default ParentComponent;

      3. ComponentC

      ComponentC
      import React from 'react'; import ComponentC1 from './ComponentC1'; function ComponentC { return( <div> <ComponentC1 /> </div> ); } export default ComponentC;

      4. ComponentC1

      ComponentC1
      import React from 'react'; import ComponentC2 from './ComponentC2'; function ComponentC1 { return( <div> <ComponentC2 /> </div> ); } export default ComponentC1;

      5. ComponentC2

      ComponentC2
      import React, { useContext } from 'react'; import { UserContext } from './ParentComponent'; function ComponentC2 { const user = useContext(UserContext) return( <div> <div> Hello {user} </div> </div> ); } export default ComponentC2;

      In above code, We create a UserContext in ParentComponent and Component C > C1 > C2. Now we have to pass one value from ParentComponent to C2 component without adding props in C and C1. So, ParentComponent is out Provider Component and C2 is Our consumer component. Provider Component is responsible to provide value to all the descendants components. ComponentC2 is consumed it by useContext hooks and use it in JSX code. Here, we all pass function from provider to consumer. We can also, use multiple context providers at a time.

 

← Previous

Next →