Created
November 17, 2021 15:21
-
-
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.
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
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