Skip to content

Instantly share code, notes, and snippets.

@danielpost
Created May 12, 2021 09:05
Show Gist options
  • Save danielpost/8b05b2da8cd401c1bd475737ac90c646 to your computer and use it in GitHub Desktop.
Save danielpost/8b05b2da8cd401c1bd475737ac90c646 to your computer and use it in GitHub Desktop.
Super simple state management in a WordPress app
/**
* Internal dependencies
*/
import ChildComponent from './ChildComponent';
import StoreProvider from './utils/store';
const App = () => (
<StoreProvider>
<ChildComponent />
</StoreProvider>
);
export default App;
/**
* 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;
// 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>;
};
// 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