Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Context API with multiple values performance

I'm using the React Context API to store many global state values (around 10 and probably more will be needed) and many components are using them. Unfortunately whenever any of the values change, all components using the useContext hook have to rerender. My current solution is to use useMemo for the return value of the components and useCallback for any complex functions and inside custom hooks I have. This addresses most of my performance concerns, but having to use the useMemo and useCallback all the time is quite annoying and missing one is quite easy. Is there a more professional way to do it?

Here's an example based on my code:

GlobalStateContext.js

import React, { useState } from 'react'

const GlobalStateContext = React.createContext({ })

export const GlobalStateProvider = ({ children }) => {
    const [config, setConfig] = useState({
        projectInfo: ''
    })
    const [projectFile, setProjectFile] = useState('./test.cpp')
    const [executionState, setExecutionState] = useState("NoProject")

    return (
        <GlobalStateContext.Provider
            value={{
                executionState,
                config,
                projectFile,
                setExecutionState,
                setConfig,
                setProjectFile,
            }}
        >
            {children}
        </GlobalStateContext.Provider>
    )
}

export default GlobalStateContext

Example.jsx

import React, { useContext } from 'react'
import GlobalStateContext from '../utils/GlobalStateContext.js'

export default Example = () => {
    const {
        executionState,
        setExecutionState,
    } = useContext(GlobalStateContext)

    return useMemo(
        () => (
            <div>
                The current execution state is: {executionState}
                <br />
                <button onClick={() => setExecutionState('Running')}>Running</button>
                <button onClick={() => setExecutionState('Stopped')}>Stopped</button>
                <button onClick={() => setExecutionState('Crashed')}>Crashed</button>
            </div>
        ),
        [
            executionState,
            setExecutionState,
        ]
    )
}
like image 398
Adam Jeliński Avatar asked Apr 08 '26 15:04

Adam Jeliński


1 Answers

Currently, this problem is unavoidable with context. There is an open RFC for context selectors to solve this, but in the meantime, some workarounds are useContextSelector and Redux, both of which prevent a subscribing component from rendering if the data it's reading did not change.

like image 131
brietsparks Avatar answered Apr 11 '26 05:04

brietsparks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!