React useContext
up:: React Hooks
import React, { useContext } from 'react';
import AuthContext from '../../store/auth-context';
// Navigation.js
const ctx = useContext(AuthContext);
return (
// all the jsx code that should have access
{ctx.isLoggedIn && <SampleComponent />} // show if user is logged in
)
Context
State chains
- If you pass a state around a lot, use context
- Or if you use a prop only to forward props but not do anything with it
- You want to avoid a lengthy ‘prop chain’
Creating a context
store/
is a common folder name
store/auth-context.js
(kebab- instead of CamelCase because it’s not a component)
import React from 'react';
const AuthContent = React.createContext({
isLoggedIn: false;
})
export default AuthContent;
You can even add functions in context!
Providing context
Wrap it around all the elements that need it.
For example, in app.js
(this makes it available to all)
import React from 'react';
import AuthContext from './store/auth-context.js'
const App = () => {
return (
<React.Fragment>
<AuthContext.Provider value={{defaultKey: defaultValue}}>
// ... rest of components
<AuthContext.Provider />
<React.Fragment />
)
}
Listening to context
Consumer (is kinda meh as a solution)
import AuthContext from '../../store/auth-context'
// Navigation.js
<AuthContext.Consumer>
{(ctx) => {
return (
// all the jsx code that should have access
{ctx.isLoggedIn && <SampleComponent />} // show if user is logged in
)
}}
<AuthContext.Consumer />