You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
285. ### What's a common pitfall when using useContext with objects?
6794
+
A **common pitfall** when using `useContext` with objects is **triggering unnecessary re-renders** across all consuming components — even when only part of the context value changes.
6795
+
6796
+
When you provide an object as the context value, React compares the entire object reference. If the object changes (even slightly), React assumes the whole context has changed, and **all components using** `useContext(MyContext)` **will re-render**, regardless of whether they use the part that changed.
6797
+
6798
+
**Example:**
6799
+
```js
6800
+
constMyContext=React.createContext();
6801
+
6802
+
functionMyProvider({ children }) {
6803
+
const [user, setUser] =useState(null);
6804
+
const [theme, setTheme] =useState('light');
6805
+
6806
+
// This causes all consumers to re-render on any state change
However, this only helps if the object structure and dependencies are well controlled.
6835
+
6836
+
**[⬆ Back to Top](#table-of-contents)**
6837
+
6838
+
286. ### What would the context value be for no matching provider?
6839
+
6840
+
When a component calls `useContext(SomeContext)` but **no matching** `**<SomeContext.Provider>**` **is present higher up in the component tree**, the **default value** passed to `React.createContext(defaultValue)` is returned.
6841
+
6842
+
```js
6843
+
constThemeContext=React.createContext('light'); // 'light' is the default value
6844
+
6845
+
functionThemedComponent() {
6846
+
consttheme=useContext(ThemeContext);
6847
+
return<div>Current theme: {theme}</div>;
6848
+
}
6849
+
6850
+
// No ThemeContext.Provider anywhere in the tree
6851
+
```
6852
+
In this case, `theme` will be 'light'. It's the default value you provided when you created the context.
6853
+
6854
+
**Note:** If you don’t specify a default value, the context value will be undefined when used without a provider:
6855
+
6856
+
```jsx
6857
+
constAuthContext=React.createContext(); // No default
6858
+
6859
+
functionProfile() {
6860
+
constauth=useContext(AuthContext);
6861
+
// auth will be undefined if there's no AuthContext.Provider
6862
+
}
6863
+
```
6864
+
6865
+
**[⬆ Back to Top](#table-of-contents)**
6866
+
6747
6867
## Old Q&A
6748
6868
6749
6869
1. ### Why should we not update the state directly?
0 commit comments