These tools/methods were made with the purpose of creating a simplified version of Redux, with much less written code.
The Context structure works as following:
const MyContext = createContext([defaultValue]);<MyContext.Provider value={ /* Context Value, can be updated */ }>
<ChildOne>
...
</MyContext.Provider>
<MyContext.Consumer>
({ contextValue, anotherValue, ... }) => (
/* Use the values as props */
)
</MyContext.Consumer>
/* App.jsx */
import React, { Component, createContext } from 'react';
export const MyContext = createContext(0);
class App extends Component {
constructor() {
...
}
}
sampleFn = () => {
this.setState(...);
}
render() {
const { state, sampleFn } = this;
return (
<MyContext.Provider value={ { ...state, sampleFn } }>
<Child />
</MyContext.Provider>
);
}
}
export default App;
/* Child.jsx */
import React from 'react';
import { MyContext } from './App';
function Child() {
return (
<MyContext.Consumer>
({ state, sampleFn }) => (
<div>
{ /* Manipulate Variables received from parent */ }
</div>
)
</MyContext.Consumer>
);
}
export default Child;
This is used to create variables for the Component, such as following:
const [counter, setCounter] = useState(0);
// let counter = 0;
setCounter(counter + 1);
// counter = 1;
This is used to retrieve variables from an external Context.