Create context factory function
See original GitHub issueDo you want to request a feature or report a bug?
feature
React.createContext
just returns the value passed in on createContext if there is no provider above in the tree.
Is it possible to get a version that takes in a factory function in the form:
createContextFn(fn:() => defaultValue)
The factory function will be invoked whenever a default value is needed.
I have two use cases for this.
- If you want to enforce the usage of a context e.g. :
createContextFn(() => throw new Error("Default value not allowed, Please use FooProvider."))
- Or you want to use a react hook as a default value:
function useTotal(){
const [total, setTotal] = useState(0);
const incFn = () => setTotal(total + 1);
return {
total,
incFn
};
}
createContextFn(useTotal)
Issue Analytics
- State:
- Created 4 years ago
- Reactions:4
- Comments:7 (3 by maintainers)
Top Results From Across the Web
What's the point of React's createContext factory function?
The only use I can think of for having the factory function is declaring a defaultValue that consequent Consumers use - for testing, ......
Read more >A Guide to React Context and useContext() Hook
const Context = createContext('Default Value');. The factory function accepts one optional argument: the default value.
Read more >Using the React Context API, the right way (a time saver)
A component factory is a function that returns a React functional component. ... We can use component factories to clean up our codebase...
Read more >JavaScript Factory Functions
A factory function is a function that returns a new object. Use Object.create() to create an object using an existing object as a...
Read more >Context Factory in EF Extensions (EFE)
The context factory is a function Func<DbContext, DbContext> that provides the current DbContext as a parameter and require to return a new DbContext....
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
How do you like this?
It doesn’t work for primitives though.
Ok… I’m doing the following to make sure it throws when used outside:
null
when creating context,