What is prop drilling and how can you avoid it?
What is prop drilling and how can you avoid it?
Prop drilling in React refers to the process of passing data from a parent component down to its child components through props. This data is then passed further down to nested child components, potentially through multiple levels of the component hierarchy, until it reaches the components that actually need the data. While this is a common pattern in React for managing state and passing data, it can lead to several issues, especially in larger applications[1][2][7].
Prop drilling can lead to:
To address the challenges of prop drilling, several strategies can be employed:
Context API:
The Context API allows you to share values between components without having to explicitly pass a prop through every level of the component tree. By creating a context, you can provide it at a high level and consume it in the components that need the data using the useContext
hook. This approach is particularly useful for data that needs to be accessible by many components at different nesting levels, such as user authentication status or theme data[2][13][14].
import React, { createContext, useContext } from 'react';
const MyContext = createContext(defaultValue);
const ParentComponent = () => {
return (
<MyContext.Provider value={someValue}>
<ChildComponent />
</MyContext.Provider>
);
};
const ChildComponent = () => {
const value = useContext(MyContext);
return <div>{value}</div>;
};
Component Composition:
Instead of passing props thro...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào