Skip to content

Instantly share code, notes, and snippets.

@EvanBurbidge
Created November 17, 2021 15:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EvanBurbidge/a71f06862aa68e1e64cded73d722d79a to your computer and use it in GitHub Desktop.
Save EvanBurbidge/a71f06862aa68e1e64cded73d722d79a to your computer and use it in GitHub Desktop.
An example of React hooks using a single data source with React context.
import { useState, createContext, useContext, useEffect } from "react";
import "./styles.css";
const AuthContext = createContext({});
const useAuth = () => useContext(AuthContext);
const AuthProvider = ({ children }) => {
const [username, setUsername] = useState("");
const handleUpdateUsername = ({ target: { value } }) => setUsername(value);
return (
<AuthContext.Provider
value={{ username, setUsername, handleUpdateUsername }}
>
{children}
</AuthContext.Provider>
);
};
const ComponentOne = () => {
const { username, setUsername } = useAuth();
useEffect(() => {
setUsername("santa");
}, []);
return <p>{username}</p>;
};
const ComponentTwo = () => {
const { username } = useAuth();
return <p>{username}</p>;
};
const ComponentThree = () => {
const { handleUpdateUsername } = useAuth();
return (
<div>
<label>Update username</label>
<br />
<input placeholder="new username" onChange={handleUpdateUsername} />{" "}
</div>
);
};
export default function App() {
return (
<AuthProvider>
<div className="App">
<ComponentOne />
<ComponentTwo />
<ComponentThree />
</div>
</AuthProvider>
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment