React, useContext

2024. 12. 5. 16:31웹 개발

ThemeContext.jsx

import React from "react";

const ThemeContext = React.createContext(); // context 생성, 초깃값 설정 없음, 프로바이더에서 설정
ThemeContext.displayName = "ThemeContext"; // 개발자 도구에 표시하기 위함

export default ThemeContext;

 

MainContext.jsx

import { useContext } from "react"; // useContext 훅 사용
import ThemeContext from "./ThemeContext";

function MainContent(props) { // ThemeContext 로부터 현재설정 테마값을 받아와 실제화면에 렌더링

    const {
        theme,
        toggleTheme
    } = useContext(ThemeContext); // useContext 훅 사용, 파라미터를 꼭 객체로 받아서 사용해야함

    return (
        <div
            style={{
                width: "100vw",
                height: "100vh",
                padding: "1.5rem",
                backgroundColor: theme == "light" ? "white" : "black",
                color: theme == "light" ? "black" : "white",
            }}
        >
            <p>안녕하세요, 테마 변경이 가능한 웹사이트 입니다.</p>
            <button onClick={toggleTheme}>테마 변경</button>
        </div>
    );
}

export default MainContent;

 

DarkOrLight.jsx

import { useState, useCallback } from "react";
import ThemeContext from "./ThemeContext";
import MainContent from "./MainContent";

function DarkOrLight(props) {

    const [theme, setTheme] = useState("light"); // state 를 사용하여 재랜더링을 막음

    const toggleTheme = useCallback(() => { // useCallback 사용
        if (theme == "light") {
            setTheme("dark");
        } else {
            setTheme("light");
        }
    }, [theme]);

    return (
        // context를 사용하여 자식 컴포넌트에게 테마와 테마 변경 함수 전달
        <ThemeContext.Provider value={{ theme, toggleTheme }}>
            <MainContent />
        </ThemeContext.Provider>
    );
}

export default DarkOrLight;

 

index.js

import React from "react";
import ReactDOM from "react-dom/client";

import DarkOrLight from "./chapter_14/DarkOrLight";

import "./index.css";

const root = ReactDOM.createRoot(document.getElementById("root"));

root.render(
    <React.StrictMode>
        <DarkOrLight />
    </React.StrictMode>
);

// https://github.com/soaple/first-met-react-practice-v18/tree/master/src

 

결과