Search code examples
reactjsreact-hooksreact-context

Listing and disabling React contexts


I am learning React so please excuse if the question is too naive.

I am currently learning about createContext and useContext.

My lecture mentioned that unnecessary re-renders can happen if the state of context changes. So I started wondering if (a) I can all contexts and (b) if I can disable one that I wish to ignore. All this to prevent unnecessary re-render.

Is there a function or attribute called useContexts.listAll or something similar that tells to any component how many contexts are available there at any moment? If it is there is it possible to ignore a context via {"myContext:{"ignore":true}} or anything similar?

Thank you.


Solution

  • Is there a function or attribute called useContexts.listAll or something similar that tells to any component how many contexts are available there at any moment?

    No there isn't. You need to know ahead of time what context you're interested in, and then you ask react for its value by doing useContext(SomeContext). Any contexts you don't ask for will not be given to you and will not automatically rerender your component. Note that your component may still rerender if it's parent component rerendered.

    For example, suppose you're designing a Theme for your app. You want to make an object with various constants defining colors, font sizes, etc. You could make a ThemeContext, and render a <ThemeContext.Provider> near the top of the app, with a value that has those constants.

    Then later, when you build a component you might decide you want to use constants found in the theme. You know about the ThemeContext, since you wrote it, so the component can call const theme = useContext(ThemeContext) to get the value. If the theme happens to change, that component will rerender.

    But in another component that doesn't need the theme, you just never call useContext(ThemeContext). It will not have access to the value, and may be able to skip rendering if the theme changes (as mentioned, it might still rerender if a parent component rerenders).

    If it is there is it possible to ignore a context via {"myContext:{"ignore":true}} or anything similar?

    If you're not interested in a context, just don't write any code that tries to access it, and it will be ignored.