DEV Community

Ramesh Vishnoi
Ramesh Vishnoi

Posted on • Updated on

State Management using Context API

In this article, we'll use Context API as State Management in our React App, same can be used in React Native app.

Context allows data to be passed down the component tree without having to pass props manually at every level.

Context is primarily used for sharing data that is global to the entire application.

Biggest advantage of using of Context is ease of onboarding into existing or new codebase without any unwanted boilerplate code. Redux comes with lot of boilerplate code and difficult to integrate.

How to Use the Context API for State Management

Step 1: Create a Context

export const AppStateContext = createContext()
Enter fullscreen mode Exit fullscreen mode

Here AppStateContext is Context value used across the app. You can create multiple context for different parts of state. For now, lets stick with only one.

Step 2: Create a Provider

const AppStateProvider = (props) => {
    const [state, setState] = useState({isLoggedIn: false})
    const reducer = (action) => {
    }
    return (
        <AppStateContext.Provider value={[state, reducer]}>
            {props.children}
        </AppStateContext.Provider>
    )
}
Enter fullscreen mode Exit fullscreen mode

Here we are making state and reducer values made available in all the components which consume this Context.

state will contain the app state (with default value as isLoggedIn = false), while reducer is function which will update state and it accepts action as a argument.

Now wrap up your app component at Root level, so that all components can access this Context.

return (
    <AppStateProvider>
        <HomeScreen />
    </AppStateProvider>
)
Enter fullscreen mode Exit fullscreen mode

Step 3: Consume context in Components.

const HomeScreen = () => {
    const [state, reducer] = useContext(AppStateContext);

    return (
        <div className="App">
            <header className="App-header">
                Is User Logged In : {state.isLoggedIn}
            </header>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Step 4: Add update state logic in reducer

 const reducer = (action) => {
    let updatedState;
    switch (action.type) {
        case 'toggleLogin':
            updatedState =  {
                ...state,
                isLoggedIn: !state.isLoggedIn
            }
    }
    setState(updatedState);
}
Enter fullscreen mode Exit fullscreen mode

Modify reducer function to accept action and update state. Here action object contain type which is used to differentiate between different actions and data as payload. for ex - pass data as api response

Step 5: Update state from component

const HomeScreen = () => {
    const [state, reducer] = useContext(AppStateContext);

    const loginNow = () => {
        reducer({type: 'toggleLogin'})
    }
    return (
        <div className="App">
            <header className="App-header">
                Is User Logged In : {state.isLoggedIn}
                <button onClick={loginNow}>Login</button>
            </header>
        </div>
    )
}
Enter fullscreen mode Exit fullscreen mode

Voila! You have a working app state management mechanism. You can follow same steps for React Native as well.

Top comments (0)