useContext Example
The useContext-hook, can be used to pass the context-methodology
to the MF-components. Although we can't subscribe to the context (because of the 'remote' part),
we can pass the context as an argument to the MF-component.
Check out this example:
Container App
File: src/AppContext.js
import { createContext } from "react"
const AppContext = createContext()
export default AppContext
File src/App.js
import React, { useState, useContext } from 'react'
import ReactDOM from 'react-dom'
import AppContext from './AppContext'
import './index.css'
import Counter from 'counter/Counter'
const App = () => {
const [txt, setTxt] = useState("Initial")
const [data, setData] = useState({ demo: "information" })
const updateText = (inputText) => {
setTxt(inputText)
}
return(
<AppContext.Provider value={{ data, updateText }}>
<h1>Container: { txt }</h1>
<Counter text={ txt } context={ AppContext } />
</AppContext.Provider>
)
};
ReactDOM.render(<App />, document.getElementById("app"))
Micro App
File: src/components/Counter.js(x)
import React, { useState, useContext } from 'react'
const Counter = ({ text, context }) => {
const [count, setCount] = useState(0)
const c = useContext(context)
const handleClick = () => {
setCount(count+1)
c.updateText(`From context, new count: ${ count }`)
}
return(
<div>
<h2>Counter App</h2>
<p>Current count: <strong>{ count }</strong></p>
<p><strong>Context:</strong>{ JSON.stringify(c.data)}</p>
<button onClick={ () => handleClick() }>
{ text }
</button>
</div>
)
}
export default Counter