Using the Context Hook Flashcards

1
Q

useContext

A

const value = useContext(MyContext);

Accepts a context object (the value returned from React.createContext) and returns the current context value for that context. The current context value is determined by the value prop of the nearest above the calling component in the tree.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

When does the useContext hook rerender?

A

When the nearest above the component updates, this Hook will trigger a rerender with the latest context value passed to that MyContext provider. Even if an ancestor uses React.memo or shouldComponentUpdate, a rerender will still happen starting at the component itself using useContext

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What argument does useContext take?

A

The argument to useContext must be the context object itself:

Correct: useContext(MyContext)
Incorrect: useContext(MyContext.Consumer)
Incorrect: useContext(MyContext.Provider)

A component calling useContext will always re-render when the context value changes. If re-rendering the component is expensive, you can optimize it by using memoization.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

useEffect, Provider & Consumer

A

If you’re familiar with the context API before Hooks, useContext(MyContext) is equivalent to static contextType = MyContext in a class, or to .

useContext(MyContext) only lets you read the context and subscribe to its changes. You still need a above in the tree to provide the value for this context.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly