React.createContext point of defaultValue?

前端 未结 2 1417
走了就别回头了
走了就别回头了 2021-02-11 13:12

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:29

    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(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

提交回复
热议问题