Prop-drilling, state management & useContext()

Prop-drilling, state management & useContext()

While working on applications in React, we generally encounter props which help us in extracting & rendering data across the components. We use props to keep ourselves away from the DRY (do not repeat) syndrome. During the course of our development, it so happens that we unknowingly start repeating ourselves so much that we don't even bother to notice the structure of the code. To avoid this situation, we make use of props and at times, we see that even using props turns out to be inefficient.

It makes sense when we use props to render a set of data in the child component from its immediate parent. But what if there is scenario where in there is a need for the parent component to send the data through props to a component which is not its immediate child ?. Under such cases, we generally go on sending the data from parent to child to grand-child to ..... until we arrive at the component that primarily needs the data. This practice of rendering the data through multiple components is what is referred to as Prop Drilling and is highly inefficient and a tedious process. During prop drilling, we un-necessarily send data to most of the components which are not even in need of. This reduces the performance of the application & hence the efficiency.

To addess this problem, we use one of the react hooks, useContext() and the Context API. These two help in creating a global state which can then be used in any of the child components without the data being passed through the component tree. Let's understand their usage to know more about them.

Recat offers createContext() method to create an instance for the global state and to pass data as a prop. The instance so created has two properties, Provider and Consumer. The component which is responsible for delivering the data acts as a provider and the component in need of the data acts as the consumer. The provider component wraps up the entire application and has a value prop with which it sends the data to the child components. Similar to how we use props in child component to extract the data, we can use the consumer and render the data.

useContext() on the other hand works with both provider & consumer and excepts the value provided by the provider component and re-render it to the child component.

Conclusion: useContext() provides a way to pass data as props from the parent component to any of the child components without having to drill into the component tree.

To understand the concept more deeply with examples, please have a look at these documents. https://reactjs.org/docs/hooks-reference.html, https://www.digitalocean.com/community/tutorials/react-usecontext