React Context API Simple Setup
Tags: javascript, react, redux
Published: 2020-11-14 16:29:23

Developing in react would probably push you to a problem called prop drilling. Basically we get some data from a API and use it and again we need it in another component😟. We call the API another time that leads to damage the quality of the website and the code.

No Problem! We could use the React Context API🔥 which is not really hard to learn as redux.

#### ⌨ Getting Started
Let's make it more simple, no more big stories 😴.

Whatever being followed down below, is under the ``` reactapp/src/ ``` directory of react app.

We are going to build a tiny wall parallel to the react application where all the required data is being held and used whenever needed 💉.

We will be needing two things to build the wall
- Some React JS Hooks
- A Reducer

#### Creating the Reducer 💊
- Create a file called ```reducer.js```
- Setting up the initial State where all the required data is going to be initialized.

```javascript
// BASICALLY A GLOBAL JSON OBJECT
export const initialState = {
// YOUR DATA
// Example: username: null
};
```
- A special function called reducer is implemented here to act as a dispatch gun to shoot out data whenever needed and to save data to the wall(data layer).

```javascript
const reducer = (state, action) => {
     switch(action.type) {
       default: return state;
     }
}

export default reducer;
```
- Here action is the bullet of the dispatch gun where you can specify the action to be taken against those data in the data layer.

#### Creating the Data Layer 🧱
- Create a file called ```DataLayer.js``` and paste the content below.
```javascript
import React, { createContext, useContext, useReducer } from "react";

// DATA LAYER !!!
export const StateContext = createContext();

export const DataLayer = ({ reducer, initialState, children }) => (
    <StateContext.Provider value={useReducer(reducer, initialState)}>
        {children}
    </StateContext.Provider>
);

// COMPONENTS USABLE HOOK
export const useDataLayerValue = () => useContext(StateContext);

```
Here first the context is created and the necessary bricks such as reducer, initial state and children are passed in. Setting up the wall itself. Children here represents each component that going to be rendered.

Finally we export a usable react hook using the created context layer.

### Fixing the DataLayer with our react app.
- Inside our ```index.js``` file, you can find the main App component.

- Surround the app component using the DataLayer component just created.

- Make sure you pass in the reducer and initialState as props.

```javascript
import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import * as serviceWorker from './serviceWorker';
import { DataLayer } from './DataLayer';
import reducer,{ initialState } from './reducer';

ReactDOM.render(
  <React.StrictMode>
    <DataLayer initialState={initialState} reducer={reducer}>
      <App />
    </DataLayer>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
```
Yey! We just completed everything setting up 😎
Now let's use the super power of Context API.

### Example of using a React Context API in real time
- Consider a react app of getting the username.
- We are going to use the data layer to store the username and use it wherever we need throughout the application.
- Let's modify some files to make that happen. In ``` reducer.js``` file.

- Create a key called username and set its value to null.
```javascript
// BASICALLY A GLOBAL JSON OBJECT
export const initialState = {
   username: null
};
```
- Now let's add some code to update it using the reducer method.
```javascript
const reducer = (state, action) => {
     switch(action.type) {
       case "SET_USERNAME": return {
                               ...state, 
                               username: action.username
                            }
                            break;
       default: return state;
     }
}
```
- Do not forget to return old state so that the data layer make changes only to the required data.
- We have just completed our dispatch gun to work.
- Use it in the component where you need that username data.
```javascript
import { useDataLayerValue } from "./DataLayer";

// USERNAME - DATA and dispatch - is a function use to shoot your actions to the data layer
const [{ username }, dispatch] = useDataLayerValue();

const changeUsername = (user) => {
// SHOOTING DATA TOWARDS THE DATA LAYER !!!
   dispatch({
     type: "SET_USERNAME",
     username: user
   });
};
```
- This piece of code just changed your data where ever you have used in your entire project in real time.

---

Find the official React Documentation at [React Doc](https://reactjs.org/docs/context.html).

Don't forget to use the GitHub Repo for React Context API, clean code that you can just use it to start building your project ♥ [@github/reactcontextapi](https://github.com/imprakashraghu/react-context-api).