Pseudo Random Nonsense Generator

React Context API + React Hooks

December 18, 2018

What’s it for?

a method to bypass prop drilling.

to fully share state in your react apps between components and be able to change state from within a child component, refer to this great tutorial.

you can only pass things through a prop called ‘value’, not anything else ( but you can put anything inside )

SET : make your shared data

make, then export your context from your top level component

// at App.js or Index.js
import React from "react";
import YourComponent from "./components/YourComponent"
import YourOtherComponent from "./components/YourOtherComponent"

// create a context (parent state)
export const MainContext = React.createContext();
const appState = {
num: 1,
callbackFunction: callbackFunction(), // you can pass functions too!
anArray: [1, 2, 3],
aString: "some words"
}

const App = props => {
return (
<MainContext.Prodiver value={appState}><YourComponent /> // no need to pass data in
<YourOtherComponent />
</MainContext.Provider>)
}
export const App;

USE : use your shared data ( Context API )

  1. import, then wrap your component with the context
// at YourComponent.js or YourOtherComponent.js
import React from 'react'
import MainContext from '../App.js'
const YourComponent = props => {
  return (
    <MainContext.Consumer>      {/_ now the stuff inside here has your shared data _/}
      {v => <p>{v.num}</p>}
    </MainContext.Consumer>  )
}
export default YourComponent

USE : use your shared data ( useContext hook )

  1. import, then assign to variable.
// at YourComponent.js or YourOtherComponent.js
import React, { useContext } from 'react'
import MainContext from '../App.js'
const YourComponent = props => {
  // now EVERYTHING in your component can use the shared data
  const sharedState = useContext(MainContext)
  return <p>{sharedState.num}</p>
}
export default YourComponent

reference

https://daveceddia.com/usecontext-hook/

https://auth0.com/blog/react-context-api-managing-state-with-ease/