TIL_47_230103

young0_0·2023년 1월 4일
0

TIL

목록 보기
46/91

47일 차 회고

  • useContext

useContext()

리액트는 부모 컴포넌트에서 자식컴포넌트로 props를 단계별로 전달해야 한다.전역적으로 Data를 전달 할때 최상위 컴포넌트에서 여러 자식컴포넌트로 단계별로 전달 해야하는데 그것을
Prop Drilling이라고 하며, 이런 비효율적인 전달이 아닌 Data가 필요한 곳에만 전달 할 수 있게 도와주는 Hook을 useContext라고 한다.

useContext는 필요 할때만 사용한다.

  • Context를 사용하면 컴포넌트를 재사용하기 어려워 질 수 있다.
  • Prop Drilling 을 피하기 위한 목적이라면 Component Composition(컴포넌트 합성)을 먼저 고려해보자

context 사용방법

1. src 에 context라는 폴더를 만들고 안에 사용할context를 만든다.

2. createContext를 import 한다.

3. export createContext(초기값)을한다.

import {createContext} from 'react'

export const ThmemeContext = createContext(null) // 기본값

4. App.js 에 import 하고 provider로 감싸고 value라는 prop을 받는다.

//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;

5. 필요한 컴포넌트에 전달한다

//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;

6. 새로운 context를 추가 하려면 context 폴더에 새로운 추가를 하고 최상위 컴포넌트에 선언한다.

// 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;
profile
열심히 즐기자ㅏㅏㅏㅏㅏㅏㅏ😎

0개의 댓글