Skip to content

Instantly share code, notes, and snippets.

@brentsowers1
Created January 23, 2021 02:12
Show Gist options
  • Save brentsowers1/b9d10c09dfadbcbc1621764203f994dd to your computer and use it in GitHub Desktop.
Save brentsowers1/b9d10c09dfadbcbc1621764203f994dd to your computer and use it in GitHub Desktop.
import React from 'react';
import globalHook from 'use-global-hook';
// You'd probably want to put this and useCounter in a separate file, and only
// export useCounter
const globalCounterActions = {
setValue: (store, newValue) => {
store.setState({ value: newValue });
},
};
const useCounter = globalHook(React, { value: 0 }, globalCounterActions);
const globalLoggedInUserActions = {
setUsername: (store, newValue) => {
store.setState({ username: newValue });
},
};
const useLoggedInUser = globalHook(React, { username: '' }, globalLoggedInUserActions);
const GlobalHookExample = () => {
return (
<div>
Main app container
<CounterDisplay />
<CounterDisplay />
<CounterIncrementer />
<LoggedInUserDisplay />
<LoggedInUserDisplay />
<LoggedInUserSetter />
</div>
);
};
const CounterIncrementer = () => {
const [counter, counterActions] = useCounter();
return (
<div>
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label,react/button-has-type */}
Increment counter - <button onClick={() => counterActions.setValue(counter.value + 1)} />
</div>
);
};
const CounterDisplay = () => {
const [counter] = useCounter();
return <div>Counter value = {counter.value}</div>;
};
const LoggedInUserSetter = () => {
const loggedInUserActions = useLoggedInUser()[1];
return (
<div>
Set logged in user name -&nbsp;
<input type="text" onChange={event => loggedInUserActions.setUsername(event.target.value)} />
</div>
);
};
const LoggedInUserDisplay = () => {
const [user] = useLoggedInUser();
return <div>Logged in user value = {user.username}</div>;
};
export default GlobalHookExample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment