0

Problem : https://codesandbox.io/s/nice-wing-zv45id?file=/src/App.js

What I am doing : I am trying to call an api from component ContextChild1 and updating the api response data in my context component BaseContextProvider. All state variables in BaseContextProvider along with setData function are being passed as a context to all the child components - ContextChild1 and ContextChild2

What is happening : ContextChild1 is getting re-executed when userData is updated in BaseContextProvider. This is working fine as it should. I know the re-execution of ContextChild1 is happening because the context is getting changed with the userData update in BaseContextProvider but this userData is NOT required by ContextChild1 instead it is required by ContextChild2.

What I want to achieve : I want ContextChild1 to NOT execute when userData state in BaseContextProvider is updated from ContextChild1.

In the demo link above, below are the series of logs you will see in console :(Ignore the (2) printed at the start of each log line in the demo)

    (2)base context provider executed    
    (2)child1 executed
    (2)child2 executed
    (2)api called from child1
    (2)base context provider executed 
    (2)child1 executed(don't want this re-render) 
    (2)child2 executed

Note : you will see below log lines as well directly after the above logs, but this is something weird I am seeing in codesandbox however this is not seen in stackblitz. So please ignore these logs as it might mislead you.

(2)base context provider executed
(2)child1 executed
(2)child2 executed
Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
utkarsh-k
  • 836
  • 8
  • 17
  • Please include the relevant code in the question itself. A code sandbox link is fine as a reference, in addition to the [mcve] in the question. – Emile Bergeron Aug 29 '22 at 20:10
  • might help https://github.com/facebook/react/issues/15156 – Giorgi Moniava Aug 29 '22 at 20:18
  • All of the techniques explained in the following answer apply to your situation: [React context with hooks prevent re render](https://stackoverflow.com/questions/57030018/react-context-with-hooks-prevent-re-render) – Emile Bergeron Aug 29 '22 at 20:21

0 Answers0