context value as a default prop?
See original GitHub issueJust had a general question regarding the “Rules of Hooks”
Don’t call Hooks inside conditions
I was curious why this wouldn’t be allowed for useContext
for the example below
const Icon = ({
spritemap = React.useContext(IconSpriteContext), // eslint complains about this
symbol,
...otherProps
}) => {
return (
<svg
{...otherProps}
role="presentation"
>
<use data-href={`${spritemap}#${symbol}`} />
</svg>
);
};
We wanted to provide both a way to use a direct prop
for the spritemap OR allow for context to be created at the top level of the app.
Any feedback is appreciated, thanks!
Issue Analytics
- State:
- Created 4 years ago
- Comments:6 (4 by maintainers)
Top Results From Across the Web
A complete guide to React default props - LogRocket Blog
Cover three ways to implement default props in React and provide default values for props that are not required by the component.
Read more >why do the context value assigned to default value?
1 Answer 1 ; I cannot use hook because I use class component. – aya abdelhaeem. May 13 at 18:59 ; do you...
Read more >react-default-props-context - npm
A DefaultPropsContext is a React context that offers a dictionary of getter functions. Each getter function corresponds to a default property ...
Read more >Typing React Context to avoid an undefined default value
In this function we create a context with a generic type and undefined as the default value, we then create another function to...
Read more >Context - React
Context provides a way to share values like these between components without having to explicitly pass a prop through every level of the...
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
Your example has a conditional call to
useContext
because it depends on the value ofspritemap
. This is why we warn.We don’t want to make the rules different for
useContext
and other Hooks. It makes it hard to refactor later when you want to changeuseContext(MyThing)
to a higher-leveluseMyThing()
Hook which might include state or effects.Interesting
then maybe it should NOT be a linter warning?, maybe the linter needs to be adjusted?