skip to Main Content

I was reading about context api in React and react docs says that createContext should be declared and run outside component. Can someone explain why? I have been trying to find articles that explain that point but no result 😔.

2

Answers


  1. It’s generally recommended to declare it outside of a component for a few reasons:

    1. Consistent reference: declaring the context outside of a component ensures that the context object reference remains consistent across renders. If the context were declared inside a component, a new instance of the context would be created every time the component re-renders. This could lead to unexpected behavior, as different instances of the context would not share the same state or references.

    2. Performance optimization: placing the createContext call outside of a component prevents unnecessary re-creation of the context on each render. Since the context object doesn’t depend on component state or props, there’s no need to create it multiple times. Declaring it outside ensures it’s created only once and shared across all instances of the component tree.

    3. Accessible to multiple components: by declaring the context outside of a component, you can make it accessible to multiple components within the application. This allows you to share data or state across different parts of your component tree without having to pass props explicitly.

    Login or Signup to reply.
  2. I just saw a presentation from Nadia during the React Summit conference that really helped me to better understand item #2 in Erez’s answer above. It might help you as well if you’re looking for more info on this topic.

    https://www.developerway.com/posts/react-re-renders-guide#part7

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