Steps to create React Application
Step 1: Create a React application using the following command:
npx create-react-app useContextReact
Step 2: After creating your project folder i.e. useContextReact, move to it using the following command:
cd useContextReact
Project Structure:
Example 1: With using Prop Drilling
Javascript
//without_useContext.js import React, { useState } from "react" ; function Parent() { const [fName, setfName] = useState( "firstName" ); const [lName, setlName] = useState( "LastName" ); return ( <> <div>This is a Parent component</div> <br /> <ChildA fName={fName} lName={lName} /> </> ); } function ChildA({ fName, lName }) { return ( <> This is ChildA Component. <br /> <ChildB fName={fName} lName={lName} /> </> ); } function ChildB({ fName, lName }) { return ( <> This is ChildB Component. <br /> <ChildC fName={fName} lName={lName} /> </> ); } function ChildC({ fName, lName }) { return ( <> This is ChildC component. <br /> <h3> Data from Parent component is as follows:</h3> <h4>{fName}</h4> <h4>{lName}</h4> </> ); } export default Parent; |
Javascript
//App.js import "./styles.css" ; import Parent from "./without_useContext" ; export default function App() { return ( <div className= "App" > <Parent /> </div> ); } |
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
What is prop drilling and how to avoid it ?
In React, prop drilling is often challenging for the efficiency and maintainability of applications. In this article we will understand prop drilling, its implications and discuss its efficient alternative.
Table of Content
- What are props?
- What is Prop Drilling?
- Why not to use prop drilling?
- Solve prop drilling with UseContext Hooks