Created
May 12, 2021 09:05
-
-
Save danielpost/8b05b2da8cd401c1bd475737ac90c646 to your computer and use it in GitHub Desktop.
Super simple state management in a WordPress app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Internal dependencies | |
*/ | |
import ChildComponent from './ChildComponent'; | |
import StoreProvider from './utils/store'; | |
const App = () => ( | |
<StoreProvider> | |
<ChildComponent /> | |
</StoreProvider> | |
); | |
export default App; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* WordPress dependencies | |
*/ | |
import { TextControl } from '@wordpress/components'; | |
/** | |
* Internal dependencies | |
*/ | |
import useSettings from './hooks/useSettings'; | |
const ChildComponent = () => { | |
const { text, setText } = useSettings(); | |
return <TextControl value={text} onChange={newText => setText(newText)} />; | |
}; | |
export default ChildComponent; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// utils/store.js | |
/** | |
* WordPress dependencies | |
*/ | |
import { createContext, useState } from '@wordpress/element'; | |
export const StoreContext = createContext(null); | |
export default ({ children }) => { | |
const [text, setText] = useState(''); | |
const store = { | |
text, | |
setText, | |
}; | |
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>; | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// hooks/useSettings.js | |
/** | |
* WordPress dependencies | |
*/ | |
import { useContext } from '@wordpress/element'; | |
/** | |
* Internal dependencies | |
*/ | |
import { StoreContext } from '../utils/store'; | |
export default () => useContext(StoreContext); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment