
Learn The useContext Hook in React
18 July, 2022
16
16
3
Contributors
Learn the useContext() Hook in React
Introduction
React Context is a way to manage state globally.
It can be used together with the useState
Hook to share state between deeply nested components more easily than with useState
alone.
It can be used to avoid props drilling.
Example of Prop Drilling
We’d be learn how to use the useContext()
by creating a simple React app with simple authentication.
Prerequisite
- Code Editor. Recommended(Visual Studio Code)
- Node js installed
- Basic knowledge of javascript.
- Basic knowledge of react-router-dom.
PS: I used Tailwind CSS for styling the React app.
Syntax
Accepts a context object (the value returned from React.createContext
) and returns the current context value for that context.
The current context value is determined by the value
prop of the nearest <MyContext.Provider>
above the calling component in the tree.
Starting code structure
Create react app using: npx create-react-app learn-usecontext-hook
Clean the provided template and add folders and files where necessary to fit the one below.
Creating the AuthContext
Consuming The AuthContext
Using the AuthContext
Controlling The Routes
Controlling The NavBar and Changing The Value of AuthContext
Changing the AuthContext in The LoginForm
Demo
Github Link
ubiquitous-parakeet/usecontexthook
Preview Url
react
javascript
react-hooks