Skip to content

Instantly share code, notes, and snippets.

@psivakrishnareddy
Last active March 6, 2022 08:00
Show Gist options
  • Select an option

  • Save psivakrishnareddy/87f75cbbcf594b0681d21a5d9ec1b97a to your computer and use it in GitHub Desktop.

Select an option

Save psivakrishnareddy/87f75cbbcf594b0681d21a5d9ec1b97a to your computer and use it in GitHub Desktop.
Quick Start Guide to Create a Context API store Setup in React

React Context API QuickStart Guide

This is a Template for Context Api in react created by Siva Krishna Reddy.

ESSENTIALS

The Context api elements include Actions, Reducers, Store, Types

Store

Create a Store in a file and Export it.

export const InitalState = {
  eventName: "",
  sportsList: [],
  skillLevel: [],
  ...
};

Types

create TYPE Constants thats used in reducer, actions Dispatch

// BASIC example
export const SET_NAME = "SET_NAME";
export const SET_SPORTS = "SET_SPORTS";
export const SET_SKILL_LEVEL = "SET_SKILL_LEVEL";

Reducer

Create a Reducer thats imported in Context

// import type constants
import {
  ATTENDEE_NAME,
  BLOOD_GROUP,
  EMAIL,
} from "../../type/ManageEvents";

//reducer method
export const ManageEventReducer = (state, action) => {
  switch (action.type) {
    case ATTENDEE_NAME:
      return {
        ...state,
        attendeeName: action.payload
      };
    case BLOOD_GROUP:
      return {
        ...state,
        bloodGroup: action.payload
      };
    case EMAIL:
      return {
        ...state,
        email: action.payload
      };
    default:
      return state;
  }
};

Create a Context Component That Creates a Provider Wrapper

import React, { createContext, useReducer } from "react";
// Store Creates and Imported Here
import { InitalState } from "../../store/AddEvent";
// Reducer Created and Imported
import { AddEventReducer } from "../../reducer/Event/AddEvent";

// Used to use the Context in other Components
export const AddEventContext = createContext();

const AddEvent = (props) => {
  const [state, dispatch] = useReducer(AddEventReducer, InitalState);
  return (
    <AddEventContext.Provider value={{ state, dispatch }}>
      {props.children}
    </AddEventContext.Provider>
  );
};

export default AddEvent:

Provider For the Component or Routes that Access this Context

The Context has a Provider that must wrap the component or route that needs to access the Store

Import the Context Component and Wrap Around that Component that need store access

import AddEvent from "../../context/Event/AddEvent";

*This Provides The Store and Reducer*
<AddEvent>
...Componeents
<AddEvent/>

AddEventContext.Provider is Wrapped around the Component with reducer and Store present in Context Component

Usage in Components or Pages

For Functional Components

Import the Context Component which is created in Conext Component File using createContext()

import { AddEventContext } from "../../context/Event/AddEvent";
Import Types to use in Dispatch function
import {
  SET_END_TIME,
  SET_START_TIME
} from "../../type/AddEventTypes";

Hooks Used To Extract the Dispatch and Store

  const { state, dispatch } = useContext(AddEventContext);

Hooks Used For Dispatching Action

*Dispatch a Action Object containing type and payload

 dispatch({
            type: SET_BASIC_DATA,
            payload: {
              levels,
              sports
            }
          });
        

For Class Components

static contextType = UserContext is used where We can extract Store data from this.context as Shown below

import React, { Component } from 'react'
import UserContext from './UserContext'

class HomePage extends Component {
  static contextType = UserContext

  componentDidMount() {
    const user = this.context

    console.log(user) // { name: 'Tania', loggedIn: true }
  }

  render() {
    return <div>{user.name}</div>
  }
}

OR

Traditional Ways uing comsumer provided consumer

import React, { Component } from 'react'
import UserContext from './UserContext'

class HomePage extends Component {
  render() {
    return (
      <UserConsumer.consumer>
        {(props) => {
          return <div>{props.name}</div>
        }}
      </UserConsumer.consumer>
    )
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment