create-react-app が生成した App.tsx に useContext を使って Login 機能を実装するための概念を説明する雑なソースコード。
App.tsx
import React, { useContext, useState } from 'react'; import './App.css'; interface User { account: string } const UserContext = React.createContext<User | null>(null); function App() { const [user, setUser] = useState<User | null>(null); const [account, setAccount] = useState(""); const [password, setPassword] = useState(""); const login = () => { console.log("login"); if(account === "miyazato" && password === "hoge"){ setUser({account: "miyazato"}); } }; const logout = () => { setUser(null); }; return ( <div className="App"> <header className="App-header"> <UserContext.Provider value={user}> <label> Account: <input onChange={ (event) => setAccount(event.target.value) }/> </label> <label> Password: <input onChange={ (event) => setPassword(event.target.value) }/> </label> <button onClick={login}>Login</button> <button onClick={logout}>Logout</button> <Content/> </UserContext.Provider> </header> </div> ); } function Content() { const user = useContext(UserContext); return ( <div> { user ? <span>LoginUser: {user?.account}</span> : <span>LoginUser: (Not Logged In)</span> } </div> ); } export default App;