LoginSignup
0
0

More than 1 year has passed since last update.

Learn createContext with TypeScript in 10 minutes で React Context の復習

Posted at

memo.

import React, {createContext, useContext, useState} from "react";

const UserContext = createContext<string | null>(null);

const UserPage: React.FC = () => {
    const context = useContext(UserContext);
    return (
        <div>{context}</div>
    )
}

const NewComponent: React.FC = () => {
    const context = useContext(UserContext);
    return (
        <div style={{background: 'red'}}>
            This is new component.<br/>
            {context}
        </div>
    )
}

export default function App() {
    const [user, setUser] = useState('Initial value')
    const handleClick = () => {
        setUser('Hello from button, ' + new Date().toDateString());
    }

    return (
        <UserContext.Provider value={user}>
            <div className="App">
                <h1>Hello from homepage.</h1>
                <button onClick={handleClick}>Change value</button>
                <UserPage/>
                <hr/>
                <NewComponent/>
            </div>
        </UserContext.Provider>
    );
}

参考資料

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0