Câu hỏi phỏng vấn Reactjs
Câu hỏi

What is prop drilling and how can you avoid it?

Câu trả lời

What is Prop Drilling?

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].

Problems Associated with Prop Drilling

Prop drilling can lead to:

  • Increased complexity: As the component tree grows, managing props passed through multiple levels becomes cumbersome and error-prone.
  • Reduced maintainability: Making changes in the structure or behavior of components can require changes across many levels of components, which is time-consuming and increases the risk of bugs.
  • Decreased component reusability: Components become tightly coupled to their specific context within the application, making them harder to reuse in different parts of the application or in different projects[1][2][7].

Strategies to Avoid Prop Drilling

To address the challenges of prop drilling, several strategies can be employed:

  1. 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>;
    };
  2. Component Composition:
    Instead of passing props thro...

middle

middle

Gợi ý câu hỏi phỏng vấn

senior

When shall we use useReducer hook in ReactJS?

senior

Why does React use SyntheticEvents ?

middle

How can I make use of Error Boundaries in functional React components?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào