단순 코드 기록/React

React_Context(Single/Multi)

일일일코_장민기 2024. 3. 18. 16:34
728x90
user-context
import { createContext } from "react";
export const UserContext = createContext("");
App
import { useState } from "react"
import Profile from "./components/Profile"
import {UserContext} from"./store/user-context"

export default function App(){

  const [username, setUsername] = useState("Mike");

  return (
    <>
    <h1>App</h1>
    {/* epxport const UserContex = createContext(""); */}
   
    <UserContext.Provider value={username}>
      <Profile></Profile>
    </UserContext.Provider>
   
    </>
  )
}

 

Greeting
import { useContext } from "react"
import { UserContext } from "../store/user-context"

export default function Greeting(){         //넘겨줄 필요 없음

const username = useContext(UserContext);   //Mike

    return <p>{`${username} provider에서 받음`}</p>;
   
}

 

profile
import Greeting from "./Greeting"
export default function Profile(){
    return <Greeting></Greeting>
}

 

 

 

 

 

 

 

 

 

 

 

user-context / theme-context
import { createContext } from "react";
export const UserContext = createContext("");

 

App
import { useState, useContext, createContext } from "react"

//멀티 context
const UserContext = createContext("unKnown");
const ThemeContext = createContext("dark");
//속성값이 없기 때문에 초기에 마운트된 이후 다시 랜더링되지 않음

function Profile(){
  return(
    <>
     <Greeting></Greeting>
    </>
  )
}

const Greeting= () => {
  const theme = useContext(UserContext);
  const username = useContext(ThemeContext);
  console.log("theme: ", theme, "username: ", username)
  return(
    <>
      <p style={{color: theme === "dark" ? "grey" : "green"}}>
        {`${username}님 안녕하세요?`}
      </p>
    </>
  )
}


export default function App(){
 
  const [name, setName] = useState({username: "mike"});
 
  return(
    <>
      <ThemeContext.Provider value={"light"}>
        <UserContext.Provider value={name}>
          <div>색 비교</div>
          <Profile></Profile>
        </UserContext.Provider>
      </ThemeContext.Provider>
   
    </>
  )
}

 

 

'단순 코드 기록 > React' 카테고리의 다른 글

React_useEffect Hook  (0) 2024.03.19
React_reducer_자식창 연동 ADD/DEL  (0) 2024.03.19
React_useReducer_글자  (0) 2024.03.18
React_useReducer_숫자 증감  (0) 2024.03.18
React_useContext로 변수와 함수 전송  (0) 2024.03.18