Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Global State — Context + useReducer

Global State — Context + useReducer

In this chapter you will learn to use React Context + useReducer to manage shared data across components and pages, and implement the 'favorite articles' feature.


Why Do We Need Global State?

So far, data has been passed down layer by layer through Props. But some data needs to be accessed by multiple unrelated components:

The pain point of passing Props down layer by layer (Prop Drilling): A → B → C → D, intermediate components are forced to receive Props they don't use.

Context provides a global 'data channel' that any descendant component can read directly, skipping intermediate layers.


Core Concepts of Context

Step Code Purpose
Creating Context createContext() Create a shared data container
Providing Data Wrap at the top of the component tree to inject data
Consuming Data useContext(MyContext) Read data in any descendant component

createContext and Provider

Example

import

{

createContext

,

useContext

,

useState

}

from

'react'

// Step 1: Create Context

const

ThemeContext

=

createContext

(

null

)

// Step 2: Create the Provider component

function

ThemeProvider

(

{

children

}

)

{

 

const

[

theme

,

setTheme

]

=

useState

(

'light'

)

 

const

toggleTheme

=

(

)

=>

setTheme

(

theme

===

'light'

?

'dark'

:

'light'

)

 

return

(

   

<

ThemeContext.

Provider

value

=

{

{

theme

,

toggleTheme

}

}

     

{

children

}

   

ThemeContext.

Provider

 

)

}

// Step 3: Use in any component

function

ThemedButton

(

)

{

 

const

{

theme

,

toggleTheme

}

=

useContext

(

ThemeContext

)

 

return

(

   

<

button onClick

=

{

toggleTheme

}

      Current theme:

{

theme

}

   

button

 

)

}

// Step 4: Wrap Provider in App

function

App

(

)

{

 

return

(

   

<

ThemeProvider

<

ThemedButton

/>

ThemeProvider

)

}

Context is like a 'broadcast tower': Provider broadcasts data outward, useContext receives the data.


useReducer — Managing Complex State

When state logic becomes complex (multiple sub-states, multiple ways to update), useState becomes inadequate.

useReducer provides a state management pattern similar to Redux: dispatch action → reducer computes the new state.

Example

import

{

useReducer

}

from

'react'

// reducer function: (current state, action) ⇒ new state

function

favoriteReducer

(

state

,

action

)

{

 

switch

(

action.

type

)

{

   

case

'TOGGLE'

:

     

// If already favorited, remove it; if not, add it

     

if

(

state.

includes

(

action.

id

)

)

{

       

return

state.

filter

(

id

=>

id

!==

action.

id

)

     

}

else

{

       

return

[

...

state

,

action.

id

]

     

}

   

case

'CLEAR'

:

     

return

[

]

   

default

:

     

return

state

 

}

}

function

FavoriteDemo

(

)

{

 

// useReducer(reducer, initial value)

 

const

[

favoriteIds

,

dispatch

]

=

useReducer

(

favoriteReducer

,

[

]

)

 

return

(

   

<

div

<

p

Favorites count:

{

favoriteIds.

length

}

p

     

<

button onClick

=

{

(

)

=>

dispatch

(

{

type

:

'TOGGLE'

,

id

:

1

}

)

}

       

{

favoriteIds.

includes

(

1

)

?

'Unfavorite 1'

:

'Favorite 1'

}

     

button

     

<

button onClick

=

{

(

)

=>

dispatch

(

{

type

:

'CLEAR'

}

)

}

Clear favorites

button

   

div

 

)

}

useState vs useReducer

Scenario Recommend Reason
Single independent state useState Simple and direct
Multiple states interrelated useReducer One dispatch can update multiple states
Complex update logic useReducer Clear action types in the reducer, easy to debug
Need to pass to deeply nested components useState or useReducer Both can be used with Context

Context + useReducer Combination Pattern

This is the most powerful global state management approach in React, and also the core idea of Redux.

Example

// File path: src/context/FavoriteContext.jsx

import

{

createContext

,

useContext

,

useReducer

,

useEffect

}

from

'react'

// 1. Create Context

const

FavoriteContext

=

createContext

(

null

)

// 2. Define the reducer

function

favoriteReducer

(

state

,

action

)

{

 

switch

(

action.

type

)

{

   

case

'TOGGLE'

:

     

if

(

state.

includes

(

action.

id

)

)

{

       

return

state.

filter

(

id

=>

id

!==

action.

id

)

     

}

else

{

       

return

[

...

state

,

action.

id

]

     

}

   

case

'CLEAR'

:

     

return

[

]

   

default

:

     

return

state

 

}

}

// 3. Provider component: combine Context + useReducer

export

function

FavoriteProvider

(

{

children

}

)

{

 

// Restore initial state from localStorage

 

const

[

favoriteIds

,

dispatch

]

=

useReducer

(

favoriteReducer

,

[

]

,

(

)

=>

{

   

const

saved

=

localStorage.

getItem

(

'blog-favorites'

)

   

return

saved

?

JSON.

parse

(

saved

)

:

[

]

 

}

)

 

// When the favorites list changes, automatically sync to localStorage

  useEffect

(

(

)

=>

{

    localStorage.

setItem

(

'blog-favorites'

,

JSON.

stringify

(

favoriteIds

)

)

 

}

,

[

favoriteIds

]

)

 

// Wrap a few common methods

 

function

toggleFavorite

(

id

)

{

    dispatch

(

{

type

:

'TOGGLE'

,

id

}

)

 

}

 

function

isFavorite

(

id

)

{

   

return

favoriteIds.

includes

(

id

)

 

}

 

const

value

=

{

    favoriteIds

,

    favoriteCount

:

favoriteIds.

length

,

    toggleFavorite

,

    isFavorite

 

}

 

return

(

   

<

FavoriteContext.

Provider

value

=

{

value

}

     

{

children

}

   

FavoriteContext.

Provider

 

)

}

// 4. Custom Hook: wrap useContext to make calls cleaner

export

function

useFavorites

(

)

{

 

const

context

=

useContext

(

FavoriteContext

)

 

if

(

!

context

)

{

   

throw

new

Error

(

'useFavorites must be used inside FavoriteProvider'

)

 

}

 

return

context

}

Register Provider in main.jsx

Example

// File path: src/main.jsx

import

React from

'react'

import

ReactDOM from

'react-dom/client'

import

{

RouterProvider

}

from

'react-router-dom'

import

{

FavoriteProvider

}

from

'./context/FavoriteContext'

import

router from

'./router'

import

'./index.css'

ReactDOM.

createRoot

(

document.

getElementById

(

'root'

)

)

.

render

(

 

<

React.

StrictMode

   

{

/* Provider wraps the outermost layer so all components can access it */

}

   

<

FavoriteProvider

<

RouterProvider router

=

{

router

}

/>

   

FavoriteProvider

 

React.

StrictMode

)

Why put Provider outside RouterProvider? Because the navigation bar NavBar (in App) also needs to read the favorites state. Provider must wrap all components that need to access this state.


Using the Favorites Feature in Components

The Favorite Button in BlogCard

Example

// File path: src/components/BlogCard.jsx

import

{

Link

}

from

'react-router-dom'

import

{

useFavorites

}

from

'../context/FavoriteContext'

function

BlogCard

(

{

id

,

title

,

summary

,

date

,

category

}

)

{

 

const

{

isFavorite

,

toggleFavorite

}

=

useFavorites

(

)

 

function

handleFavorite

(

e

)

{

    e.

preventDefault

(

)

 

// Prevent Link navigation

    toggleFavorite

(

id

)

 

}

 

return

(

   

<

Link to

=

{

`

/

post

/

$

{

id

}

`

}

className

=

"card-link"

     

<

div className

=

"card"

       

<

span className

=

"tag"

{

category

}

span

       

<

h3

{

title

}

h3

<

p

{

summary

}

p

<

div className

=

"card-footer"

         

<

span className

=

"date"

{

date

}

span

         

<

button className

=

"fav-btn"

onClick

=

{

handleFavorite

}

           

{

isFavorite

(

id

)

?

'♥'

:

'♡'

}

         

button

       

div

     

div

   

Link

 

)

}

export

default

BlogCard

The Favorite Button in PostPage

Example

// File path: src/pages/PostPage.jsx (key part)

import

{

useFavorites

}

from

'../context/FavoriteContext'

function

PostPage

(

)

{

 

// ... other code

 

const

{

isFavorite

,

toggleFavorite

}

=

useFavorites

(

)

 

return

(

   

<

article className

=

"post-view"

     

<

div className

=

"post-header"

       

<

h1

{

article.

title

}

h1

       

<

button className

=

"fav-btn"

onClick

=

{

(

)

=>

toggleFavorite

(

article.

id

)

}

         

{

isFavorite

(

article.

id

)

?

'♥ Favorited'

:

'♡ Favorite'

}

       

button

     

div

     

{

/* ... */

}

   

article

 

)

}

Displaying the Favorites Count in NavBar

Example

// File path: src/components/NavBar.jsx

import

{

useFavorites

}

from

'../context/FavoriteContext'

function

NavBar

(

)

{

 

const

{

favoriteCount

}

=

useFavorites

(

)

 

return

(

   

<

header className

=

"navbar"

     

<

a href

=

"/"

className

=

"logo"

RUNOOB Blog

a

     

<

nav

<

a href

=

"/"

Home

a

       

{

favoriteCount

0

&&

(

         

<

span className

=

"fav-badge"

Favorite

{

favoriteCount

}

span

       

)

}

     

nav

   

header

 

)

}

After favoriting an article on the home page, the detail page automatically shows 'Favorited', and the number in the navigation bar updates synchronously - this is the value of Context global sharing.


Context + useReducer vs Vue3 Pinia

Feature React Context + useReducer Vue3 Pinia
Integration methods Built into React, no installation needed Standalone library, requires installation
State Definition Initial value of useReducer state: () => ({})
State Update dispatch({ type, payload }) Direct modification or action function
Computed Properties Manual useMemo getters
Reactive approach Provider value change triggers re-render Automatic dependency tracking
DevTools None built-in (requires Redux DevTools) Native support in Vue DevTools

Chapter Summary

In this chapter you mastered the complete solution for React global state management: createContext creates the container, Provider injects data, useContext consumes data, and useReducer manages complex update logic.

The 'favorite articles' feature keeps data on the home page, detail page, and navigation bar globally synchronized, and can be restored via localStorage after a page refresh.