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. As a result, 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 context API works like a tree. The consumer component needs to be inside the tree. Therefore, the consumer will not work outside of the scope of the tree.

In the end, how we can get the context value inside a class-based or a functional component. The following two sections will explain that with examples:

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>
    )
};
Reference: