title: React - accessing context in componentDidMount
body: <p>I'm using Context API for the first time and I'm having some difficulties to understand how to update context in lifecycle methods. I had a look at the <a href="https://reactjs.org/docs/context.html#accessing-context-in-lifecycle-methods" rel="nofollow noreferrer">official doc</a> and this <a href="https://stackoverflow.com/questions/49809884/access-react-context-outside-of-render-function/49810870#49810870">answer</a> which made sense but didn't help me much to find a solution.</p>
  
  <p>I have 2 components for now: one parent and one child. </p>
  
  <p>In the parent, I'm using an axios get() request in componentDidMount() to fetch data.</p>
  
  <p>The child uses context to render elements so it needs the updated context once the request is complete. </p>
  
  <p>My main issue is I can't find out where to update the provider state once the axios response is received. Ideally I'd like to assign the axios response to the provider state but I can't figure out how to access the context from there.</p>
  
  <p>I made it "work" by assigning the axios response to the parent state then by updating the context provider state with it through a handler from my Provider and called this handler in render() under my Consumer since it's the only place I believe I have access to the context:</p>
  
  <pre><code>class ParentComponent extends Component {
      render() {
          return (
              &lt;MyContext.Consumer&gt;
                  {(context) =&gt; {
                      if(axiosSuccess) {context.updateContextState(parentState);}
                      return (
                          &lt;ChildComponent/&gt;
                      )
                  }}
              &lt;/MyContext.Consumer&gt;
          );
      }
  }
  </code></pre>
  
  <p>However I know it's not the right implementation since updating in render() is an anti-pattern.</p>
  
  <p>What is the best way to update provider state in lifecycle methods?</p>