47일 차 회고
- useContext
리액트는 부모 컴포넌트에서 자식컴포넌트로 props를 단계별로 전달해야 한다.전역적으로 Data를 전달 할때 최상위 컴포넌트에서 여러 자식컴포넌트로 단계별로 전달 해야하는데 그것을
Prop Drilling이라고 하며, 이런 비효율적인 전달이 아닌 Data가 필요한 곳에만 전달 할 수 있게 도와주는 Hook을 useContext라고 한다.
import {createContext} from 'react'
export const ThmemeContext = createContext(null) // 기본값
//App.js
import React,{useState}from 'react'
import {ThemeContext} from './context/ThemeContext'
function App(){
const [isDark, setIsDark] = useSate(false)
return (
<ThemeContext.Provider value={{isDark, setIsDark}}>
<Page />
</ThemeContext.Provider>
)
}
export default App;
//Header.js
import React from 'react';
import {ThemeContext} from './context/ThemeContext'
function Header(){
const {isDark} = useContext(ThemeContext)
return (
<header
style={{
backgroundColor:isDark ? 'black' : 'lightgray',
color: isDark ? 'white' : 'black'
}}
>
<h1>Welcom</h1>
</header>
)
}
export default Header;
//Contents.js
import React from 'react';
import {ThemeContext} from './context/ThemeContext'
function Content(){
const {isDark} = useContext(ThemeContext)
return (
<div
style={{
backgroundColor:isDark ? 'black' : 'lightgray',
color: isDark ? 'white' : 'black'
}}
>
<p>happy</p>
</header>
)
}
export default Content;
//footer.js
import React from 'react';
import {ThemeContext} from './context/ThemeContext'
function Footer(){
const {isDark,setIsDark} = useContext(ThemeContext)
const toggleTheme = ()=>{
setIsDark(!isDark)
}
return (
<div
style={{
backgroundColor:isDark ? 'black' : 'lightgray',
color: isDark ? 'white' : 'black'
}}
>
<button onClick={toggleTheme}>다크모드</button>
</div>
)
}
export default Footer;
// UserContext.js
import {createContext} from 'react'
export const UserContext = createContext(null) // 기본값
//App.js
import React,{useState}from 'react'
import {ThemeContext} from './context/ThemeContext'
import {UserContext} from './context/UserContext'
function App(){
const [isDark, setIsDark] = useSate(false)
return (
<UserContext.Provider value={'사용자'}>
<ThemeContext.Provider value={{isDark, setIsDark}}>
<Page />
</ThemeContext.Provider>
</UserContext.Provider>
)
}
export default App;
//Header.js
import React from 'react';
import {ThemeContext} from './context/ThemeContext'
import {userContext} from './context/userContext'
function Header(){
const {isDark} = useContext(ThemeContext)
const user = useContext(userContext)
return (
<header
style={{
backgroundColor:isDark ? 'black' : 'lightgray',
color: isDark ? 'white' : 'black'
}}
>
<h1>{user}Welcom</h1>
</header>
)
}
export default Header;