State Management using Context API
Tags: react, webdev, programming, javascript
Published: 2023-03-17 15:44:04

---
title: State Management using Context API
published: true
description: State Management example using Context API for React and React Native codebase.  
tags: react, webdev, programming, javascript
# cover_image: https://github.com/rameshvishnoi90904/Banner-Images/blob/master/Banner.png?raw=true
# Use a ratio of 100:42 for best results.
# published_at: 2023-03-17 14:06 +0000
---


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()
```

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>
    )
}
```

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>
)
```

#### 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>
    )
}
```

#### 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);
}
```
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>
    )
}
```

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