React 进阶面试题, Context API
React 进阶面试题, Context API
QA
Step 1
Q:: What is Context API in React and why is it used?
A:: Context API in React is a way to manage state globally. It allows you to create global variables that can be passed around the component tree without having to pass props manually at every level. It is used to avoid 'prop drilling' or passing props through multiple levels of components when only one or two components need the data.
Step 2
Q:: How do you create a Context in React?
A:: You create a context in React by using the React.createContext()
function.
This function returns a context object with a Provider
and Consumer
component.
The Provider
component is used to wrap the part of the component tree where you want the context to be available,
and it accepts a value
prop that holds the data you want to pass down.
Step 3
Q:: How do you consume or use Context in a component?
A:: You can consume context in a component by using the useContext
hook or by using the Consumer
component provided by the context object.
The useContext
hook allows you to directly retrieve the context value without needing to use the Consumer
component.
Step 4
Q:: Can you provide an example of how to update the context value?
A:: To update the context value,
you typically pass a function down through the context that updates the state in the parent component where the context Provider
is defined. For example, you might have a function that updates a state variable, and you pass that function as part of the context value.
Step 5
Q:: What are the limitations or downsides of using Context API?
A:: While Context API is powerful, it is not a replacement for a state management library like Redux. It is not designed for very large applications with deeply nested component trees or for cases where many components need to re-render frequently. Excessive use of context can also lead to performance issues if not managed properly.