DEV Community

Cover image for Do you need global state?
Tom Mitchelmore
Tom Mitchelmore

Posted on • Edited on

Do you need global state?

It's no secret that global state is an absolute nightmare - and not just in React. In this post I'm going to show you how to use the Context API and possibly save you the headache of setting up Redux.

The Context API

React's Context API is often overlooked by newer developers because it's not talked about as it probably should be. In short, it provides utilities for nested access to a value.

Have you ever had some state and passed it down through several layers of components? This is called Prop Drilling and it feels awkward for good reason - it's inefficient and really difficult to refactor! Context solves this problem.

Setting up Context

Imagine you're building a dashboard page to display information about a user - you could have several components that all need to consume that data:

Create a file called UserContext.ts:

import { createContext } from 'React'

const UserContext = createContext<User | null>(null)

export default UserContext
Enter fullscreen mode Exit fullscreen mode

Providing Context to a component tree

Use the Context Provider in the top level of the dashboard:

import UserContext from './UserContext'

function Dashboard() {
  const user: User = {
    name: "Tom",
    email: "hello@mitchelmore.dev"
  }

  return (
    <UserContext.Provider value={user}>
       ...
    </UserContext.Provider>
  )
}

export default Dashboard
Enter fullscreen mode Exit fullscreen mode

Consuming Context

Accessing our context is as simple as passing it to one of React's built-in hooks:

import { useContext } from 'react'
import UserContext from './UserContext'

function DisplayUser() {
  const user = useContext(UserContext)

  if (user === null) throw new Error("...")

  return (<div>{user.name}</div>)
}
Enter fullscreen mode Exit fullscreen mode

It really is that simple - and it's something I discovered far too late into my journey with React.

When not to use Context

While Context is great for eliminating prop drilling - there are definitely scenarios where I'd be reaching for Redux:

Complex data

If your data is a giant nested object, then a global state library is something I'd definitely recommend. Redux, for example, will help you split it into manageable "slices" and also let you define actions to get and mutate data at your will.

Server-synchronised data

A much more sustainable approach to web app development is storing all data server-side and having the frontend reflect it. This completely eliminates global state on the frontend, and prevents issues with saving data as the backend is the single source of truth. Tanstack Query (formerly React Query) is by far the best and most popular solution - I'd highly recommend it!

Conclusion

To conclude, the purpose of this article is to help you understand how understanding React and its ecosystem can help you make architectural decisions. Far too often people spend hours setting up a library like Redux (increasing their bundle size!) just for functionality that could've been perfectly achieved with context.

Top comments (0)