DEV Community

Sospeter Mong'are
Sospeter Mong'are

Posted on

Understanding `useContext` in React (Simple Global State)

4. Understanding useContext (Simple Global State)

Why useContext Exists

Passing props through many layers is called prop drilling.

Example:

App → Layout → Sidebar → Profile → Avatar
Enter fullscreen mode Exit fullscreen mode

Only Avatar needs the data 😩


What Is Context?

Context lets you:

  • Store data once
  • Access it anywhere below

Think:

“Make this data global.”


Simple Context Example

const UserContext = React.createContext();

function App() {
  const [user, setUser] = useState(null);

  return (
    <UserContext.Provider value={{ user, setUser }}>
      <Dashboard />
    </UserContext.Provider>
  );
}
Enter fullscreen mode Exit fullscreen mode

Using it:

const { user } = useContext(UserContext);
Enter fullscreen mode Exit fullscreen mode

When to Use Context

Good for:

  • Logged-in user
  • Theme
  • Language
  • App-wide settings

Bad for:

  • Frequently changing data
  • Very complex logic

Common Beginner Mistake

Using Context for everything.

Context is not Redux.


Key Takeaway

Context is great for simple global data, not complex app logic.

Top comments (0)