|
This article demonstrates the use of Context API to avoid prop drilling in React. We will learn about the following concepts: Table of Content What are Props ?Props are basically information (properties) that is passed from the parent component to other components (children) in React.They are objects that are used to share and communicate data between different components in a react application. What is Prop Drilling ?Prop drilling is the situation where developers pass props (data) to multiple levels of components until the component where required data is reached. For example, if we have a GrandParent, a Parent and a Child component and we need data pass the GrandParent component to the Child component then using prop drilling we need to pass the data from GrandParent component to the Parent component and from the parent component to the child component.Prop drilling leads to several issues, such as an increase in the complexity of the project and a performance issue as passing down large objects into several components decreases the overall performance. Context API:To address the issue of prop drilling contextAPI is used. It allows the developers to easily share the information with different components that are not directly connected. Use the Context API to Avoid Prop drilling:
Steps to Create Project:Step 1: Create React application: npx create-react-app my-app
Step 2: Navigate to the root folder by using the command: cd my-app
Step 3: Create two files ChildA.js and ChildB.js in the src folder as shown Approach:
Example: Write the following code in respective files. Javascript
Javascript
Javascript
Start your application using the following command: npm start
Output: |
Reffered: https://www.geeksforgeeks.org
ReactJS |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |