[React] Context API

The Context API (React 16.3)

The context API is usually used for global data. This can help with the overly complicated props-chain.

In /context/auth-context.js

1
2
3
4
5
6
7
8
import React from 'react';

const authContext = React.createContext({
authenticated: false,
login: () => {}
}); // The context could also be any other types of value: number, string, etc

export default authContext;

To use context in application: wrap the components that need context data into the context component.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// App.js
return ( // Providing the authenticated value to all the children
<Cockpit/>
<button>
</button>
<AuthContext.Provider value={{
authenticated: this.state.authenticated,
login: this.loginHandler}}>
{persons}
</AuthContext.Provider>
)

// Consume context data
// Person.js
import { AuthContext} from '../../../containers/App';

render() {
return (
<Aux>
<AuthContext.Consumer>
{(context) => context.authenticated ? <p>Authenticated </p> : <p>Please sign in</p>}
</AuthContext.Consumer>
</Aux>
)
}

contextType and useContext

1
2
3
4
5
6
7
8
9
10
11
import AuthContext from './context/auth-context';

class Person extends Component {
constructor () {...}

static contextType = AuthContext; // gives a new context property to the component

componentDidMount() {
console.log(this.context.authenticated); // context is offered by React
}
}

useContext() in React Hooks.

1
2
3
4
5
6
7
8
import { useContext } from 'react';
import AuthContext from './context/auth-context';

const component = props => {
const authContext = useContext(AuthContext);

console.log(authContext.authenticated);
}