React UseContext is Simple

In Parent component or App.js, we just need to create & export the context, literally by using the createContext hooks! Simply use these few lines of code:

// in App.js
import {createContext} from ‘react’;
export const contextToPassDown = create…


This content originally appeared on DEV Community and was authored by yqgoh

In Parent component or App.js, we just need to create & export the context, literally by using the createContext hooks! Simply use these few lines of code:

// in App.js
import {createContext} from 'react';
export const contextToPassDown = createContext();

Then wrap the context Provider over the child components you wish to provide the context

   <contextToPassDown.Provider value={dataToPassDown}>
        <ChildComponent />
   </contextToPassDown.Provider>

Then in any Child components that are wrapped by the tag, we just need to use the useContext hooks!

// in ChildComponent.js
import {useContext} from 'react';
import {contextToPassDown} from App.js;

const ChildComponent=()=>{
  const contextToUse = useContext(contextToPassDown);

  return (<div> {contextToUse.username} </div>);
}

export default ChildComponent;

The use cases for useContext are usually:

  1. To Pass down logged-in user info to authorized components
  2. For 'light' or 'dark' theme

You may practice using this link to: codesandbox


This content originally appeared on DEV Community and was authored by yqgoh


Print Share Comment Cite Upload Translate Updates
APA

yqgoh | Sciencx (2021-11-09T02:40:21+00:00) React UseContext is Simple. Retrieved from https://www.scien.cx/2021/11/09/react-usecontext-is-simple/

MLA
" » React UseContext is Simple." yqgoh | Sciencx - Tuesday November 9, 2021, https://www.scien.cx/2021/11/09/react-usecontext-is-simple/
HARVARD
yqgoh | Sciencx Tuesday November 9, 2021 » React UseContext is Simple., viewed ,<https://www.scien.cx/2021/11/09/react-usecontext-is-simple/>
VANCOUVER
yqgoh | Sciencx - » React UseContext is Simple. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/11/09/react-usecontext-is-simple/
CHICAGO
" » React UseContext is Simple." yqgoh | Sciencx - Accessed . https://www.scien.cx/2021/11/09/react-usecontext-is-simple/
IEEE
" » React UseContext is Simple." yqgoh | Sciencx [Online]. Available: https://www.scien.cx/2021/11/09/react-usecontext-is-simple/. [Accessed: ]
rf:citation
» React UseContext is Simple | yqgoh | Sciencx | https://www.scien.cx/2021/11/09/react-usecontext-is-simple/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.