

dark mode), you can put a context provider at the top of your app, and use that context in components that need to adjust their visual look. Theming: If your app lets the user change its appearance (e.g.If neither of these approaches works well for you, consider context. This reduces the number of layers between the component specifying the data and the one that needs it. Instead, make Layout take children as a prop, and render. For example, maybe you pass data props like posts to visual components that don’t use them directly, like. If you pass some data through many layers of intermediate components that don’t use that data (and only pass it further down), this often means that you forgot to extract some components along the way. Extract components and pass JSX as children to them.
REACT CONTEXTS CODE
It may feel like a slog, but it makes it very clear which components use which data! The person maintaining your code will be glad you’ve made the data flow explicit with props. If your components are not trivial, it’s not unusual to pass a dozen props down through a dozen components. Here’s a few alternatives you should consider before using context: Just because you need to pass some props several levels deep doesn’t mean you should put that information into context. Before you use contextĬontext is very tempting to use! However, this also means it’s too easy to overuse it. One component may use or provide many different contexts without a problem. Each context that you make with createContext() is completely separate from other ones, and ties together components using and providing that particular context. Similarly, different React contexts don’t override each other. You can set all ’s color to red without impacting background-color. In CSS, different properties like color and background-color don’t override each other. Similarly, in React, the only way to override some context coming from above is to wrap children into a context provider with a different value. In CSS, you can specify color: blue for a, and any DOM node inside of it, no matter how deep, will inherit that color unless some other DOM node in the middle overrides it with color: green. How context works might remind you of CSS property inheritance. Try it in the sandbox above!Ĭontext lets you write components that “adapt to their surroundings” and display themselves differently depending on where (or, in other words, in which context) they are being rendered. A Section specifies the context for the tree inside it, so you can insert a anywhere, and it will have the correct size. You didn’t do anything special for this to work.
