skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. There’s no such functionality. But essentially any context you can import from another file is available to you, but unless some parent components provides a value, you’ll always get a default value that you provided to createContext function.

    It’s all explained here, although slightly out of order: Passing Data Deeply with Context

    Just read the entire page and you’ll likely understand.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search