How to access react context outside of render function in ReactJS?

React context API is the alternative of redux. It is very useful for managing states in ReactJS. We can very easily reduce the props passing hell from component to component. It works as a global state where the provider will add data and the consumer will consume data as they need.

The important note about context API is that it works like a tree. The consumer component has to be inside the tree. The consumer will not work outside of the scope of the tree. Now we get an obvious question that how we can get the context value inside a class-based or a functional component.

How to access context inside class-based component?

import AppContext from "../AppContext";
class Checkout extends React.Component {
    static contextType = AppContext;
    componentDidMount() {
        const contextValue = this.context;

    }
    render() {
        return (
          <Fragment> <h2>Hello world {contextValue}</h2> </Fragment>
        )
    }
}

How to access context inside a functional component?

import AppContext from "../AppContext";
const SubscriptionList = () =>{
    const contextValue = useContext(AppContext);

    return(
        <Fragment> <h2>Hello world {contextValue}</h2> </Fragment>
    )
};
Share