Suggestion: useProvider for replacing context.Provider
See original GitHub issuefunction App(props) {
const [theme] = useState({color: 'white'})
const [user] = useState({name: 'rabbit'})
useProvider(themeContext, theme)
useProvider(userContext, user)
/* ... */
}
is equivalent to
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
theme: {color: 'white'},
user: {name: 'rabbit'}
}
}
render() {
return (
<themeContext.Provider value={this.state.theme}>
<userContext.Provider value={this.state.user}>
</userContext.Provider>
</themeContext.Provider>
)
}
}
Issue Analytics
- State:
- Created 5 years ago
- Reactions:6
- Comments:7 (1 by maintainers)
Top Results From Across the Web
A Guide to React Context and useContext() Hook
The React context provides data to components no matter how deep they are in the components hierarchy.
Read more >Context - React
All consumers that are descendants of a Provider will re-render whenever the Provider's value prop changes. The propagation from Provider to its descendant ......
Read more >javascript - How to update the Context value in a Provider from ...
The easiest way to do this is to make an empty function that accepts the parameters, to be replaced later by the setState...
Read more >Create your own React context - Medium
The current context creation API returns a Provider wrapper component, and the state-of-the-art way to access the context value is through ...
Read more >How to use React Context effectively - Kent C. Dodds
How to create and expose React Context providers and consumers. ... The React docs suggest that providing a default value "can be helpful...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Providers intentionally don’t work this way because the notion of tree structure actually has a meaning (unlike Hooks like
useState
). Your proposal makes it more difficult to move code between components because any Hook could contain auseProvider
call inside, invisibly affecting everything below.Yes it’s not a good pattern to make provider a hook, but why not attach all the Contexts to the root element of the Component? It don’t break the tree structure.
Or make a multiple provider(don’t use contexts.reduce inside, instead, use only one layer in the tree):
similar to
we need tree structure between context and component, but don’t need that between contexts.
It doesn’t make a significant difference unless one use many contexts, but just looks more make sense.