Search
 
SCRIPT & CODE EXAMPLE
 

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();
Comment

PREVIOUS NEXT
Code Example
Javascript :: hasownproperty javascript 
Javascript :: prevstate in react 
Javascript :: How to Display a List in React 
Javascript :: fs fstat 
Javascript :: javascript polling 
Javascript :: chart.js clear data 
Javascript :: index of 
Javascript :: object.keys mdn 
Javascript :: switch to window in testcafe 
Javascript :: react native make safe view in mobile 
Javascript :: component vs container react 
Javascript :: how to get a due date from current date in javascript 
Javascript :: js history 
Javascript :: react-native-community/blur 
Javascript :: dynamic array in javascript 
Javascript :: Reduce array to a single string using reduce 
Javascript :: SyntaxError: await is only valid in async function 
Javascript :: javascript press tab key 
Javascript :: javascript divide string into two parts 
Javascript :: vim go back word 
Javascript :: compare object array equals 
Javascript :: react image source showing object module 
Javascript :: js string replace array 
Javascript :: usb react native device not found 
Javascript :: web3 get network name 
Javascript :: react bootstrap table 
Javascript :: vuelidate required if another props 
Javascript :: js array split by comma 
Javascript :: javascript variable in html string 
Javascript :: tab key event in angular 
ADD CONTENT
Topic
Content
Source link
Name
3+5 =