
React - What is Prop Drilling?
Requirements
- React.js
Introduction
Prop drilling is the action you take to pass data though React Components as props.
Let's say you have this scenario, where you are passing props to a from
parent function:
import React, { useState } from "react"; function Child(props) { return <GrandChild value={props.value} />; } function GrandChild(props) { return <h1>{props.value}</h1>; } export default function App() { const [num, setNum] = useState(8); return <Child value={num} />; }
Problem
Problem?
This functionality is very useful and straight forward, it's simply passing values through props of parent component to children. You can easily track all places it's used and debug, change or refactor everything without having to run the code and update.
Problem!
Prop drilling can be good in some scenarios but as the app grows, it can become overwhelming tracking all the layers of components passing props.
Solution
To resolve this problem we can use React's own Context API, Redux(Toolkit!), MobX, among many state management solutions out there. These solutions wrap the entire app with prop state that can be grabbed and used only where you need them, then you can choose what piece of data you want to be local or global.
Additional Resources
Related Posts
- What is React memo?2021-08-31
- What is React's Context API?2021-08-28
- React - What is Prop Drilling?2021-08-28