Q1. How do you create a context?
Use
This returns an object with
Example:
React.createContext(defaultValue).This returns an object with
Provider and Consumer properties.Example:
const ThemeContext = React.createContext('light');Q2. What is the Provider component?
It accepts a
Any component that consumes this context will get the nearest Provider's value.
Provider is a component that makes the context value available to all its descendants.It accepts a
value prop.Any component that consumes this context will get the nearest Provider's value.
Q3. What happens if a consumer is not wrapped in a Provider?
If no Provider is found, the consumer will use the
This is useful for testing or when no provider is needed.
defaultValue passed to createContext.This is useful for testing or when no provider is needed.
Q4. Can you nest providers?
Yes, you can nest multiple providers, each for different contexts.
Also, you can override a context value by placing a new Provider deeper in the tree.
The nearest Provider's value is used.
Also, you can override a context value by placing a new Provider deeper in the tree.
The nearest Provider's value is used.
Q5. How do you update context value?
The Provider's value can be state from a parent component.
When that state changes, the Provider re-renders and all consumers will update.
Example:
When that state changes, the Provider re-renders and all consumers will update.
Example:
const [theme, setTheme] = useState('dark'); <ThemeContext.Provider value={{ theme, setTheme }}>.