Course contentsShow
← React Native
Lesson 362 of 1,5554. Flexbox and Native StylingFree lesson

Global Style Injection via Context

Broadcast design tokens throughout the component tree for uniform brand application.

In this lesson, you will learn how to use the React Context API to broadcast design tokens—like brand colors and spacing units—across your entire component tree for a unified look.

The Problem: Hardcoded Styles

When building a professional app, you likely have a brand palette (e.g., specific shades of blue, standardized padding). If you hardcode these values into every StyleSheet.create call, updating your brand identity becomes a nightmare. If the "Primary Blue" changes, you’d have to manually hunt through every file to update it.

The Solution: Global Injection

By leveraging Context, we can "inject" our design tokens into the component tree once at the root, making them available to any child component without manually passing props through every layer.

Step 1: Create the Theme Context

First, we define our design tokens in a central object:

const theme = {
  colors: { primary: '#007AFF', background: '#FFFFFF' },
  spacing: { small: 8, medium: 16 }
};

const ThemeContext = React.createContext(theme);

Step 2: Provide the Tokens

Wrap your application's entry point with the Provider. This makes the theme object accessible to every screen and button within your app:

export default function App() {
  return (
    <ThemeContext.Provider value={theme}>
      <MainNavigator />
    </ThemeContext.Provider>
  );
}

Step 3: Consume in Components

Any component can now "subscribe" to these tokens using the useContext hook. This ensures that when you apply a style, you aren't referencing a hardcoded number, but a living brand token:

const MyButton = () => {
  const { colors, spacing } = useContext(ThemeContext);
  
  return (
    <View style={{ padding: spacing.medium, backgroundColor: colors.primary }}>
      <Text>Tap Me</Text>
    </View>
  );
};

By decoupling your raw values from your visual components, you create a system where design changes can happen in one file, instantly propagating throughout your entire mobile interface. This makes your layout architecture significantly more maintainable and consistent.

Key Takeaway: Global Style Injection uses Context to bridge the gap between your design tokens and your UI components, ensuring that brand consistency is maintained automatically as your app grows.