0
0
React Nativemobile~3 mins

Why global state avoids prop drilling in React Native - The Real Reasons

Choose your learning style9 modes available
The Big Idea

What if you never had to pass data through endless layers again?

The Scenario

Imagine you have a family photo album. To show a picture to your cousin, you have to pass the album through many relatives first. Each relative just passes it along without looking. This is like passing data through many components that don't need it, just to reach the one that does.

The Problem

Passing data through many layers is slow and confusing. If you want to change the data, you must update every relative who passes it. It's easy to make mistakes or forget a step, causing bugs and frustration.

The Solution

Global state acts like a shared photo album in the living room. Everyone who needs the picture can see it directly without asking others to pass it along. This makes sharing data simple, fast, and less error-prone.

Before vs After
Before
import React, { useState } from 'react';
function Parent() {
  const [name, setName] = useState('Alice');
  return <Child1 name={name} />;
}
function Child1({ name }) {
  return <Child2 name={name} />;
}
function Child2({ name }) {
  return <Display name={name} />;
}
function Display({ name }) {
  return <Text>{name}</Text>;
}
After
import React, { createContext, useState, useContext } from 'react';
import { Text } from 'react-native';
const NameContext = createContext();
function Parent() {
  const [name, setName] = useState('Alice');
  return <NameContext.Provider value={name}><Display /></NameContext.Provider>;
}
function Display() {
  const name = useContext(NameContext);
  return <Text>{name}</Text>;
}
What It Enables

Global state lets any part of your app access shared data instantly, making your code cleaner and easier to manage.

Real Life Example

Think of a shopping app where the cart total updates everywhere instantly without passing the total through every screen manually.

Key Takeaways

Passing data through many components is slow and error-prone.

Global state shares data directly with any component that needs it.

This makes apps simpler, faster, and easier to maintain.