Skip to content

Instantly share code, notes, and snippets.

@adarsh0d
Created May 5, 2020 10:07
Show Gist options
  • Save adarsh0d/a6a7a6d730b85b6f709005803bf6bbdc to your computer and use it in GitHub Desktop.
Save adarsh0d/a6a7a6d730b85b6f709005803bf6bbdc to your computer and use it in GitHub Desktop.
useContext.js
import React, {useState, useContext} from 'react';
const Context = React.createContext()
const App = () => {
const [fontSize, updateFontSize] = useState(14);
return (
<Context.Provider value={{fontSize: fontSize, updateFontSize: (val) => updateFontSize(val)}}>
<Child1></Child1>
<Context.Provider>
)
}
const Child1 = () => {
//Nothing to do with context
return (
<Child2></Child2>
)
}
const Child2 = () => {
//Nothing to do with context
return (
<Child3></Child3>
)
}
const Child3 = () => {
//want to access the context
const {fontSize, updateFontSize} = useContext(Context);
return (
<input value={fontSize} onChange={(e) => updateFontSize(e.target.value)}></input>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment