๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • GDG on campus Ewha Tech Blog
3-1๊ธฐ ์Šคํ„ฐ๋””/React Native

[4์ฃผ์ฐจ] Hooks์™€ Context API

by krkorklo 2021. 11. 17.

๐Ÿ”Ž 6์žฅ Hooks

Hooks๋Š” ๋ฆฌ์•กํŠธ 16.8 ๋ฒ„์ „์— ์ƒˆ๋กญ๊ฒŒ ์ถ”๊ฐ€๋œ ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค. Hooks๋ฅผ ์‚ฌ์šฉํ•ด ์ปดํฌ๋„ŒํŠธ ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜๊ฑฐ๋‚˜ ์ƒ๋ช… ์ฃผ๊ธฐ์— ๋”ฐ๋ผ ํŠน์ • ์ž‘์—…์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

6.1 useState

useState ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•˜๋ฉด ๋ณ€์ˆ˜์™€ ๊ทธ ๋ณ€์ˆ˜๋ฅผ ์ˆ˜์ •ํ•  ์ˆ˜ ์žˆ๋Š” setter ํ•จ์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

const Counter = () => {
  const [count, setCount] = useState(0);

  return (
    <>
      <StyledText>count: {count}</StyledText>
      <Button title="+" onPress={() => setCount(count + 1)} />
      <Button title="-" onPress={() => setCount(count - 1)} />
    </>
  );
};

 

โ“ ์„ธํ„ฐ ํ•จ์ˆ˜

  • ์„ธํ„ฐ ํ•จ์ˆ˜์— ๋ณ€๊ฒฝ๋  ์ƒํƒœ์˜ ๊ฐ’์„ ์ „๋‹ฌ
  • ์„ธํ„ฐ ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ์— ํ•จ์ˆ˜๋ฅผ ์ „๋‹ฌ

๊ทธ๋ƒฅ ๋ณ€๊ฒฝ๋  ์ƒํƒœ์˜ ๊ฐ’์„ ์ „๋‹ฌํ•˜๋Š” ๊ฒฝ์šฐ ์•„๋ž˜ ์ฝ”๋“œ์˜ setCount๊ฐ€ ํ•œ ๋ฒˆ๋ฐ–์— ์ž‘๋™ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค.

onPress={() => {
	setCount(count + 1)
	setCount(count + 1)
}}

โ— ์„ธํ„ฐ ํ•จ์ˆ˜๊ฐ€ ๋น„๋™๊ธฐ๋กœ ๋™์ž‘ํ•˜๊ธฐ ๋•Œ๋ฌธ์— ์„ธํ„ฐ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•ด๋„ ๋ฐ”๋กœ ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋˜์ง€ ์•Š๋Š” ๊ฒƒ

→ ์„ธํ„ฐ ํ•จ์ˆ˜์— ํ•จ์ˆ˜๋ฅผ ์ธ์ž๋กœ ์ „๋‹ฌํ•ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

onPress={() => {
	setCount(prevCount => prevCount + 1);
	setCount(prevCount => prevCount + 1);
}}

→ setCount๊ฐ€ ๋‘ ๋ฒˆ ์ž‘๋™ํ•ฉ๋‹ˆ๋‹ค.

 


 

6.2 useEffect

useEffect๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋ Œ๋”๋ง ๋  ๋•Œ๋งˆ๋‹ค ์›ํ•˜๋Š” ์ž‘์—…์ด ์‹คํ–‰๋˜๋„๋ก ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋Š” ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.

const Form = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  useEffect(() => {
    console.log(`name: ${name}, email: ${email}`);
  });

  return (
    <>
      <StyledText>Name: {name}</StyledText>
      <StyledText>Email: {email}</StyledText>
      <StyledTextInput
        value={name}
        onChangeText={(text) => setName(text)}
        placeholder="name"
      />
      <StyledTextInput
        value={email}
        onChangeText={(text) => setEmail(text)}
        placeholder="email"
      />
    </>
  );
};

 

โ“ ํŠน์ • ์กฐ๊ฑด์—์„œ ์‹คํ–‰ํ•˜๊ธฐ

ํŠน์ • ์ƒํƒœ๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ๋งŒ ํ˜ธ์ถœํ•˜๊ณ  ์‹ถ์€ ๊ฒฝ์šฐ ๋‘ ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ์— ์ƒํƒœ ๊ด€๋ฆฌ ๋ณ€์ˆ˜๋ฅผ ๋ฐฐ์—ด๋กœ ์ „๋‹ฌํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

useEffect(() => {
    console.log(`name: ${name}, email: ${email}`);
  }, [email]);

→ email์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งŒ useEffect๊ฐ€ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.

 

โ“ ๋งˆ์šดํŠธ๋  ๋•Œ ์‹คํ–‰ํ•˜๊ธฐ

๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰ํ•˜๋„๋ก ์„ค์ •ํ•˜๊ณ  ์‹ถ์œผ๋ฉด ๋‘ ๋ฒˆ์งธ ํŒŒ๋ผ๋ฏธํ„ฐ์— ๋นˆ ๋ฐฐ์—ด์„ ์ „๋‹ฌํ•˜๋ฉด ๋ฉ๋‹ˆ๋‹ค.

useEffect(() => {
    console.log(`name: ${name}, email: ${email}`);
  }, []);

 

โ“ ์–ธ๋งˆ์šดํŠธ๋  ๋•Œ ์‹คํ–‰ํ•˜๊ธฐ

useEffect ๋งˆ์ง€๋ง‰์— ๋ฆฌํ„ด๋ฌธ์„ ์‚ฌ์šฉํ•˜๋ฉด ํ•ด๋‹น ๊ตฌ๋ฌธ์€ ์–ธ๋งˆ์šดํŠธ ๋  ๋•Œ ์‹คํ–‰๋ฉ๋‹ˆ๋‹ค.

useEffect(() => {
    console.log(`name: ${name}, email: ${email}`);
		return () => console.log('unmount\\n');
  }, []);

 


 

6.3 useRef

Javascript์—์„œ ํŠน์ • DOM์„ ์„ ํƒํ•  ๋•Œ getElementById์™€ ๊ฐ™์€ ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค. ๊ฐ™์€ ์ƒํ™ฉ์— ๋ฆฌ์•กํŠธ์—์„œ๋Š” ref๋ฅผ ์‚ฌ์šฉํ•ด ์ปดํฌ๋„ŒํŠธ๋ฅผ ์„ ํƒํ•ฉ๋‹ˆ๋‹ค.

useRef๋Š” ํŠน์ • ์ปดํฌ๋„ŒํŠธ๋ฅผ ์„ ํƒํ•ด์•ผ ํ•˜๋Š” ์ƒํ™ฉ์—์„œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” Hook์ž…๋‹ˆ๋‹ค.

const Form = () => {
  const [name, setName] = useState("");
  const [email, setEmail] = useState("");

  const refName = useRef(null);
  const refEmail = useRef(null);

  useEffect(() => {
    console.log(`name: ${name}, email: ${email}`);
    refName.current.focus();
  }, []);

  return (
    <>
      <StyledText>Name: {name}</StyledText>
      <StyledText>Email: {email}</StyledText>
      <StyledTextInput
        value={name}
        onChangeText={(text) => setName(text)}
        placeholder="name"
        ref={refName}
        returnKeyType="next"
        onSubmitEditing={() => refEmail.current.focus()}
      />
      <StyledTextInput
        value={email}
        onChangeText={(text) => setEmail(text)}
        placeholder="email"
        ref={refEmail}
        returnKeyType="done"
      />
    </>
  );
};

๋‹ค์Œ๊ณผ ๊ฐ™์ด ์„ค์ •ํ•ด๋†“์œผ๋ฉด ์ฒ˜์Œ focus๊ฐ€ refName์œผ๋กœ ํ–ฅํ•˜๊ณ  return key๋ฅผ ๋ˆ„๋ฅด๋ฉด refEmail๋กœ focus๊ฐ€ ํ–ฅํ•ฉ๋‹ˆ๋‹ค.

โ— ํ•ด๋‹น ๋ณ€์ˆ˜๊ฐ€ ์•„๋‹ˆ๋ผ ๋ณ€์ˆ˜์˜ .current ํ”„๋กœํผํ‹ฐ์— ํ•ด๋‹น ๊ฐ’์„ ๋‹ด์Šต๋‹ˆ๋‹ค.

 


 

6.4 useMemo

useMemo๋Š” ๋™์ผํ•œ ์—ฐ์‚ฐ์˜ ๋ฐ˜๋ณต ์ˆ˜ํ–‰์„ ์ œ๊ฑฐํ•ด ์„ฑ๋Šฅ์„ ์ตœ์ ํ™”ํ•ฉ๋‹ˆ๋‹ค.

const getLength = (text) => {
  console.log(`Target Text: ${text}`);
  return text.length;
};

const list = ["javascript", "expo", "expo", "react native"];

let idx = 0;

const Length = () => {
  const [text, setText] = useState(list[0]);
  const [length, setLength] = useState("");

  const _onPress = () => {
    setLength(getLength(text));
    ++idx;
    if (idx < list.length) setText(list[idx]);
  };

  return (
    <>
      <StyledText>Text: {text}</StyledText>
      <StyledText>Lenght: {length}</StyledText>
      <Button title="Get Length" onPress={_onPress} />
    </>
  );
};

ํ•ด๋‹น ์ฝ”๋“œ๋ฅผ ์‹คํ–‰ํ•ด๋ณด๋ฉด ๋งˆ์ง€๋ง‰ ๊ฐ’ ์ดํ›„์— ๋ฌธ์ž์—ด์˜ ๋ณ€ํ™”๊ฐ€ ์—†์Œ์—๋„ getLength ํ•จ์ˆ˜๊ฐ€ ๊ณ„์† ํ˜ธ์ถœ๋ฉ๋‹ˆ๋‹ค.

const _onPress = () => {
    ++idx;
    if (idx < list.length) setText(list[idx]);
  };
  const length = useMemo(() => getLength(text), [text])

→ useMemo๋ฅผ ์‚ฌ์šฉํ•ด text๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งŒ ํ•จ์ˆ˜๋ฅผ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 


 

6.5 ์ปค์Šคํ…€ Hooks ๋งŒ๋“ค๊ธฐ

ํŠน์ • API์— GET ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ์‘๋‹ต์„ ๋ฐ›๋Š” Hook ํ•จ์ˆ˜๋ฅผ ๋งŒ๋“ค์–ด๋ด…์‹œ๋‹ค

export const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url);
        const result = await res.json();
        if (res.ok) {
          setData(result);
          setError(null);
        } else {
          throw result;
        }
      } catch (error) {
        setError(error);
      }
    };
    fetchData();
  }, []);
  return { data, error };
};
const { data, error } = useFetch(URL)

๊ฐ„๋‹จํ•˜๊ฒŒ Hook์„ ๋งŒ๋“ค๊ณ  ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

โ— ๋Œ€๋ถ€๋ถ„์˜ ๋น„๋™๊ธฐ ์ž‘์—… ํ™”๋ฉด์—์„œ๋Š” ์ž‘์—…์ด ์™„๋ฃŒ๋˜๊ธฐ ์ „์— ํ™”๋ฉด ์ „์ฒด๋‚˜ ํŠน์ • ๋ฒ„ํŠผ์ด ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๋Š” ์ƒํƒœ๊ฐ€ ๋ฉ๋‹ˆ๋‹ค.

→ API ์š”์ฒญ์˜ ์ง„ํ–‰ ์ƒํƒœ๋ฅผ ์•Œ ์ˆ˜ ์žˆ์–ด์•ผ ๋น„๋™๊ธฐ ์š”์ฒญ ์ž‘์—… ์ƒํ™ฉ์— ๋”ฐ๋ผ ํ™”๋ฉด ๊ตฌ์„ฑ์„ ๋‹ฌ๋ฆฌ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

→ inProgress ์ƒํƒœ ์ถ”๊ฐ€

export const useFetch = (url) => {
  const [data, setData] = useState(null);
  const [error, setError] = useState(null);
  const [inProgress, setInProgress] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setInProgress(true);
        const res = await fetch(url);
        const result = await res.json();
        if (res.ok) {
          setData(result);
          setError(null);
        } else {
          throw result;
        }
      } catch (error) {
        setError(error);
      } finally {
        setInProgress(false);
      }
    };
    fetchData();
  }, []);
  return { data, error, inProgress };
};
return (
	<>
		{inProgress && (
			<LoadingMessage>Loading...</LoadingMessage>
		)}
		<StyledImage source={data?.message ? { uri: data.message } : null />
		<ErrorMessage>{error?.message}</ErrorMessage>
	</>
)

โ— ์ž์ฃผ ์‚ฌ์šฉ๋˜๋Š” ๋ถ€๋ถ„์„ ๋ถ„๋ฆฌํ•ด Hooks๋กœ ๋งŒ๋“ค๋ฉด ๊น”๋”ํ•˜๊ฒŒ ์žฌ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•ฉ๋‹ˆ๋‹ค.

 

 


 

 

๐Ÿ”Ž 7์žฅ Context API

์ปดํฌ๋„ŒํŠธ๊ฐ€ ์•„๋‹ˆ๋ผ ์ „์—ญ์ ์œผ๋กœ ์ƒํƒœ๋ฅผ ๊ด€๋ฆฌํ•˜๊ธฐ ์œ„ํ•ด Context API๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

7.1 ์ „์—ญ ์ƒํƒœ ๊ด€๋ฆฌ

๋ฐ์ดํ„ฐ๋Š” ๋ถ€๋ชจ ์ปดํฌ๋„ŒํŠธ์—์„œ ์ž์‹ ์ปดํฌ๋„ŒํŠธ๋กœ ์ „๋‹ฌ๋ฉ๋‹ˆ๋‹ค.

๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ปดํฌ๋„ŒํŠธ๊ฐ€ ๋งŽ์€ ๊ฒฝ์šฐ ๊ด€๋ฆฌํ•˜๋Š” ์ƒํƒœ๊ฐ€ ์ถ”๊ฐ€๋˜๊ฑฐ๋‚˜ ๋ณ€๊ฒฝ๋˜๋Š” ๊ฒฝ์šฐ ๋ชจ๋“  ๊ณผ์ •์˜ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ˆ˜์ •ํ•ด์•ผํ•œ๋‹ค๋Š” ๋ฌธ์ œ๊ฐ€ ์žˆ์Šต๋‹ˆ๋‹ค.

→ Context API๋ฅผ ์‚ฌ์šฉํ•ด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 


 

7.2 Context API

import { createContext } from 'react'

const UserContext = createContext({ name: "Kim" });

export default UserContext;

 

โ“ Consumer

Context ์˜ค๋ธŒ์ ํŠธ๋Š” ๊ธฐ๋ณธ๊ฐ’, Consumer, Provider ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ฐ€์ง€๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค.

Consumer ์ปดํฌ๋„ŒํŠธ๋Š” ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ ์ค‘ ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด ๊ณณ์— ์žˆ๋Š” Provider ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์ „๋‹ฌํ•˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ’ก ์ƒ์œ„ ์ปดํฌ๋„ŒํŠธ ์ค‘ Provider ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์—†๋‹ค๋ฉด createContext ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ์ „๋‹ฌ๋œ ๊ธฐ๋ณธ๊ฐ’์„ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

// src/components/User.js
import React from 'react';
import styled from 'styled-components';
import UserContext from '../contexts/User';

const StyledText = styled.Text`
	font-size: 24px;
	margin: 10px;
`

const User = () => {
	return(
		<UserContext.Consumer>
			{value => <StyledText>Name: {value.name}</StyledText>}
		</UserContext.Consumer>
	)
}

export default User;
// src/App.js
import User from './components/User'

const App = () => {
	return (
		<Container>
			<User/>
		</Container>
	)
}

 

โ“ Provider

Provider ์ปดํฌ๋„ŒํŠธ๋Š” ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์— Context์˜ ๋ณ€ํ™”๋ฅผ ์•Œ๋ฆฌ๋Š” ์—ญํ• ์„ ํ•ฉ๋‹ˆ๋‹ค. value๋ฅผ ๋ฐ›์•„์„œ ๋ชจ๋“  ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ์— ์ „๋‹ฌํ•˜๊ณ  ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ๋Š” Provider ์ปดํฌ๋„ŒํŠธ์˜ value๊ฐ€ ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค ๋‹ค์‹œ ๋ Œ๋”๋ง๋ฉ๋‹ˆ๋‹ค.

// src/App.js
import UserContext from './contexts/User';

const App = () => {
	return (
		<UserContext.Provider value={{ name: "kim" }}>
			<Container>
				<User/>
			</Container>
		</UserContext.Provider>
	)
}

Provider๋กœ ๊ฐ์‹ธ๋ฉด User ์ปดํฌ๋„ŒํŠธ์—์„œ ์‚ฌ์šฉ๋œ Consumer ์ปดํฌ๋„ŒํŠธ๋Š” ๋”์ด์ƒ Context์˜ ๊ธฐ๋ณธ๊ฐ’์„ ์‚ฌ์šฉํ•  ์ˆ˜ ์—†๊ธฐ ๋•Œ๋ฌธ์— Provider์—์„œ value๋ฅผ ์„ ์–ธํ•ด์ฃผ์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.

Provider ์ปดํฌ๋„ŒํŠธ๋กœ๋ถ€ํ„ฐ value๋ฅผ ์ „๋‹ฌ๋ฐ›๋Š” ํ•˜์œ„ ์ปดํฌ๋„ŒํŠธ ์ˆ˜์—๋Š” ์ œํ•œ์ด ์—†์ง€๋งŒ, Consumer ์ปดํฌ๋„ŒํŠธ๋Š” ๊ฐ€์žฅ ๊ฐ€๊นŒ์šด Provider ์ปดํฌ๋„ŒํŠธ์—์„œ ๊ฐ’์„ ๋ฐ›์Šต๋‹ˆ๋‹ค.

 

โ“ Context ์ˆ˜์ •ํ•˜๊ธฐ

// src/contexts/User.js
import React, { createContext, useState } from 'react';

const UserContext = createContext({
	user: { name: '' },
	dispatch: () => {},
});

const UserProvider = ({ children }) => {
	const [name, setName] = useState("Kim");

	const value = { user: { name }, dispatch: setName };
	return <UserContext.Provider value={value}>{children}</UserContext.Provider>;
}

const UserConsumer = UserContext.Consumer;

export { UserProvider, UserConsumer };
export default UserContext;

Provider ์ปดํฌ๋„ŒํŠธ์˜ value์— ์ „์—ญ์ ์œผ๋กœ ๊ด€๋ฆฌํ•  ์ƒํƒœ ๋ณ€์ˆ˜์™€ ์ƒํƒœ๋ฅผ ๋ณ€๊ฒฝํ•˜๋Š” ํ•จ์ˆ˜๋ฅผ ํ•จ๊ป˜ ์ „๋‹ฌํ•˜๋Š” UserProvider ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ƒ์„ฑํ•ฉ๋‹ˆ๋‹ค.

ํ•ด๋‹น UserProvider๋Š” ๊ธฐ์กด์˜ ์ปดํฌ๋„ŒํŠธ์™€ ๋‹ฌ๋ฆฌ ํ•˜์œ„์— ์žˆ๋Š” Consumer ์ปดํฌ๋„ŒํŠธ์˜ ์ž์‹ ํ•จ์ˆ˜์˜ ํŒŒ๋ผ๋ฏธํ„ฐ๋กœ ๋ฐ์ดํ„ฐ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ๋ฐ์ดํ„ฐ๋ฅผ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ๋Š” ํ•จ์ˆ˜ dispatch๋„ ํ•จ๊ป˜ ์ „๋‹ฌํ•ฉ๋‹ˆ๋‹ค.

// src/App.js
import { UserProvider } from './contexts/User';

const App = () => {
	 return (
		<UserProvider>
			<Container>
				<User />
			</Container>
		</UserProvider>
	)
}
...
// src/components/User.js
import React from 'react';
import styled from 'styled-components';
import { UserConsumer } from '../contexts/User';

const User = () => {
	return (
		<UserConsumer>
			{({ user }) => <StyledText>name: {user.name}</StyledText>}
		</UserConsumer>
	)
}

→ ๊ฐ„๋‹จํ•˜๊ฒŒ Provider์™€ Consumer๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

์ƒํƒœ๊ฐ’์„ ์‚ฌ์šฉํ• ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ ํ•จ๊ป˜ ์ „๋‹ฌ๋œ ์„ธํ„ฐํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ๊ฐ’์„ ๋ณ€๊ฒฝํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

// src/components/Input.js
import React, { useState } from 'react';
import { UserConsumer } from '../contexts/User';

const Input = () => {
	const [name, setName] = useState('');

	return (
		<UserConsumer>
			{({ dispatch }) => {
				return (
					<TextInput
						value={name}
						onChangeText={text => setName(text)}
						onSubmitEditing={() => {
							dispatch(name);
							setName('');
						}}
						autoCorrect={false}
						autoCapitalize="none"
						returnKeyType="done"
					/>
				)
			}}
		</UserConsumer>
	)
}

export default Input;

useState๋ฅผ ์‚ฌ์šฉํ•ด name์˜ ์ƒํƒœ ๋ณ€์ˆ˜๋ฅผ ์ƒ์„ฑํ•˜๊ณ  TextInput ์ปดํฌ๋„ŒํŠธ์— ๊ฐ’์ด ๋ณ€๊ฒฝ๋  ๋•Œ๋งˆ๋‹ค name์— ๋ฐ˜์˜๋˜๋„๋ก ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ๊ทธ๋ฆฌ๊ณ  dispatch๋ฅผ ์‚ฌ์šฉํ•ด ํ‚ค๋ณด๋“œ์˜ ํ™•์ธ ๋ฒ„ํŠผ์„ ๋ˆ„๋ฅด๋ฉด TextInput์˜ ์ปดํฌ๋„ŒํŠธ์— ์ž…๋ ฅ๋œ ๊ฐ’์œผ๋กœ Context์˜ ๊ฐ’์ด ๋ณ€๊ฒฝ๋ฉ๋‹ˆ๋‹ค.

 


 

7.3 useContext

useContext Hook์„ ์‚ฌ์šฉํ•ด Context๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

// src/components/User.js
import React, { useContext } from 'react';
import UserContext from '../contexts/User';

const User = () => {
	const { user } = useContext(UserContext);
	return <Text>name: {user.name}</Text>
}
...
// src/components/Input.js
import React, { useState, useContext } from 'react';
import UserContext from '../contexts/User';

const Input = () => {
	const [name, setName] = useState('');
	const { dispatch } = useContext(UserContext);

	return (
		<TextInput
			value={name}
			onChangeText={text => setName(text)}
			onSubmitEditing={() => {
				dispatch(name);
				setName('');
			}}
			autoCorrect={false}
			autoCapitalize="none"
			returnKeyType="done"
		/>
	)
}

useContext๋ฅผ ์‚ฌ์šฉํ•ด ํŽธํ•˜๊ฒŒ Context๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

๋Œ“๊ธ€