React.createContext point of defaultValue?

前端 未结 2 1674
不知归路
不知归路 2021-02-11 13:10

On the React 16 Context doc page, they have examples that look similar to this:

const defaultValue = \'light\';
const SomeContext = React.createContext(defaultVa         


        
相关标签:
2条回答
  • 2021-02-11 13:30

    My two cents:

    After reading this instructive article by Kent C. Dodds as usual :), I learnt that the defaultValue is useful when you destructure the value returned by useContext:

    Define the context in one corner of the codebase without defaultValue:

    const CountStateContext = React.createContext() // <-- define the context in one corner of the codebase without defaultValue
    

    and use it like so in a component:

    const { count } = React.useContext(CountStateContext)
    

    JS will obviously say TypeError: Cannot read property 'count' of undefined

    But you can simply not do that and avoid the defaultValue altogether.

    About tests, my teacher Kent has a good point when he says:

    The React docs suggest that providing a default value "can be helpful in testing components in isolation without wrapping them." While it's true that it allows you to do this, I disagree that it's better than wrapping your components with the necessary context. Remember that every time you do something in your test that you don't do in your application, you reduce the amount of confidence that test can give you.

    Extra for TypeScript; if you don't want to use a defaultValue, it's easy to please the lint by doing the following:

    const MyFancyContext = React.createContext<MyFancyType | undefined>(undefined)
    

    You only need to be sure to add the extra validations later on to be sure you have covered the cases when MyFancyContext === undefined

    • MyFancyContext ?? 'default'
    • MyFancyContext?.notThatFancyProperty

    etc

    0 讨论(0)
  • 2021-02-11 13:45

    When there's no Provider, the defaultValue argument is used for function createContext. This is helpful for testing components in isolation without wrapping them, or testing it with different values from Provider.

    0 讨论(0)
提交回复
热议问题