Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

react context api with hooks

//AppContextProvider.js
import React, { createContext, useContext, useState } from 'react';

const AppContext = createContext(undefined);

// Hook to provide access to context object
export const UseAppContext = () => {
  return useContext(AppContext);
};

export const AppContextProvider = (props) => {
  const [apiData, setApiData] = useState([]);
  const globalValue = "Global Value"

  // Assign React state and constants to context object
  const AppContextObject = {
    apiValue:{
          apidata, setApiData
    },
    global:{
          globalValue  
    } 
  };
  return (
    <AppContext.Provider value={AppContextObject}>
      {props.children}
    </AppContext.Provider>
  );
};

// USAGE
// In app.js
<AppContextProvider>
   <App />
</AppContextProvider>

// In Child Component
const {
    global:{
          globalValue  
    },
    apiValue:{
          apidata, setApiData
    }
  } = UseAppContext();
 
PREVIOUS NEXT
Tagged: #react #context #api #hooks
ADD COMMENT
Topic
Name
8+9 =