Skip to content

Instantly share code, notes, and snippets.

@brentsowers1
Last active January 26, 2021 02:44
Show Gist options
  • Save brentsowers1/2be104dc3a2b5baca4b179c36d29cc8f to your computer and use it in GitHub Desktop.
Save brentsowers1/2be104dc3a2b5baca4b179c36d29cc8f to your computer and use it in GitHub Desktop.
import React from 'react';
import { useCounter, useLoggedInUser } from './sharedState';
const CounterIncrementer = () => {
// This looks like useState, but it's shared. So whenever any other component
// calls setCounter, the counter value here will update. And calling
// setCounter here will update any other component using it.
const [counter, setCounter] = useCounter();
return (
<div>
<div>Current value in incrementer component - {counter}</div>
<div>
{/* eslint-disable-next-line jsx-a11y/control-has-associated-label,react/button-has-type */}
Increment - <button onClick={() => setCounter(old => old + 1)} />
</div>
</div>
);
};
const CounterDisplay = () => {
const [counter] = useCounter();
return <div>Counter value in display component - {counter}</div>;
};
const LoggedInUserSetter = () => {
const setUser = useLoggedInUser()[1];
return (
<div>
Set logged in user name -&nbsp;
<input type="text" onChange={event => setUser(event.target.value)} />
</div>
);
};
const LoggedInUserDisplay = () => {
const [user] = useLoggedInUser();
return <div>Logged in user value in display component - {user}</div>;
};
const SharedStateHookExample = () => {
return (
<div>
Main app container
<CounterDisplay />
<CounterDisplay />
<CounterIncrementer />
<LoggedInUserDisplay />
<LoggedInUserDisplay />
<LoggedInUserSetter />
</div>
);
};
export default SharedStateHookExample;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment