Home > Back-end >  useContext is not updating some components while it is working fine for others
useContext is not updating some components while it is working fine for others

Time:09-29

I am using Context to work with cross-component state. I have 3 levels of component, all component have access to the context using useContext but the thing is whenever the changes to the context takes place it is reflected in the middle level component but the other two is only showing the initial state. I can't think of something that can be wrong. help me out if possible.

enter image description here

CodePudding user response:

It depends on how many Context.Provider you have used.

const Branch = ({ theme1, theme2 }) => {
  return (
    <ThemeContext.Provider value={theme1}>
      // A. value = theme1
      <ThemeContext.Provider value={theme2}>
        // B. value = theme2
      </ThemeContext.Provider>
      // C. value = theme1
    </ThemeContext.Provider>
    // D value = defaultTheme
  )
}

You can have different values for location A,B,C, and D. Article explaining this problem, https://javascript.plainenglish.io/react-context-is-a-global-variable-b4b049812028.

  • Related