Photo by Lautaro Andreani on Unsplash
How to use React Context API for state Management.
Alternative to "prop drilling"
Context API is a new feature added in version 16.3 of React that allows one to share the state across the entire app. It is light and easy to use. The React Context API is a feature in React that allows you to manage the global state of your application without the need for passing props through intermediate components. It provides a way to share data between components that are nested deep in the component tree.
This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on. Context is also touted as an easier, lighter approach to state management using Redux.
Actions-plain js objects to describe what happened.
{
type:'SET_TOKEN',
description:_token,
}
Reducer.js - job of the reducer is to return a new state on the action provided. Reducer is a pure function.
export const initialState ={
user: null,
playlists: [],
spotify: null,
discover_weekly: null,
top_artists: null,
playing: false,
item: null,
};
// Action -> type,[payload]
export const reducer=(state,action)=>{
switch(action.type){
case'SET_USER':
return {
...state,
user:action.user
};
case "SET_PLAYLISTS":
return{
...state,
playlists : action.playlists,
};
case "SET_ITEM":
return {
...state,
item: action.item,
};
case "SET_DISCOVER_WEEKLY":
return {
...state,
discover_weekly: action.discover_weekly,
};
case "SET_TOP_ARTISTS":
return {
...state,
top_artists: action.top_artists,
};
case "SET_TOKEN":
return {
...state,
token: action.token,
};
case "SET_SPOTIFY":
return {
...state,
spotify: action.spotify,
};
case "SET_PLAYLISTS":
return {
...state,
playlists: action.playlists,
};
default:
return state;
}
}
DataLayer.js- Creating a DataLayer (like STORE in Redux) or the global state of your application without the need for passing props through intermediate components. It provides a way to share data between components that are nested deep in the component tree.
import React ,{createContext ,useContext,useReducer} from 'react';
export const DataLayerContext = createContext ();
export const DataLayer = ({initialState,reducer,children})=>(
<DataLayerContext.Provider value={useReducer(reducer,initialState)}>
{children}
</DataLayerContext.Provider>
);
export const useDataLayerValue =()=>useContext(DataLayerContext);
Dispatching action in App.js
dispatch works as a trigger and goes to the reducer through the DataLayer to check the case we have put in the reducer and the action it will return to the initialState ={...}; and change it.
dispatch({ //this will pop in the user in the Data Layer
type:'SET_USER',
user:user,
});
dispatch({ //this will pop in the token in the Data Layer
type:'SET_TOKEN',
token:_token,
});
const[{user,token},dispatch]= useDataLayerValue();
//dispatch can pull any point{user,token} in the component tree from DataLayer