본문 바로가기

Study/React

[React Native] useContext

useContext는 장면전환시 값을 넘겨받기 위해 사용하며, 단독으로 사용할 수 없다.

이 때 createContext를 같이 사용해야 한다.

// TextProvider.tsx

import React, { createContext } from "react";

export const TextContext = createContext({});

interface Props {
    children: JSX.Element
}

export default function TextProvider({children}:Props) {

    const text = "전달하는 값";

    return (
        <TextContext.Provider value={text}>
            {children}
        </TextContext.Provider>
    );
}

// CountProvider.tsx

import React, { createContext, useState } from "react";

export const CountContext = createContext({});

interface Props {
    children: JSX.Element
}

export const CountProvider = ({children}:Props) => {

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


    return (
        <CountContext.Provider value={[count, setCount]}>
            {children}
        </CountContext.Provider>
    );
}

컴포넌트는 다음과 같이 작성된다.


// components

import React, { useContext } from "react";
import { Text, View } from "react-native";
import SecondComponent from "./SecondComponent";
import { TextContext } from "./TextProvider";

export default function FirstComponent() {

    // const textData = useContext(TextContext);
    // return (
    //     <View>
    //         <Text>First Component</Text>
    //         <Text>{textData}</Text>
    //         <SecondComponent />
    //     </View>
    // );

    return (
        <View>
            <Text>First Component</Text>
            {/* <Text>{textData}</Text> */}
            <SecondComponent />
        </View>
    );
}

import React, { useContext } from "react";
import { Text, View } from "react-native";
import ThirdComponent from "./ThirdComponent";

export default function SecondComponent() {


    return (
        <View>
            <Text>Second Component</Text>
            <ThirdComponent />
        </View>
    );
}

import React, { useContext } from "react";
import { Button, Text, View } from "react-native";
import { CountContext } from "./CountProvider";
import { TextContext } from "./TextProvider";

export default function ThirdComponent() {

    // const textData = useContext(TextContext);

    // return (
    //     <View>
    //         <Text>Third Component</Text>
    //         <Text>{textData}</Text>
    //     </View>
    // );

    const [count, setCount]:any = useContext(CountContext);

    const btnClick = () => {
        setCount((pcount:any) => pcount + 1)
    }

    return (
        <View>
            <Text>Third Component</Text>
            <Text>현재 카운트 : {count}</Text>
            <Button title="+1 증가" onPress={btnClick} />
        </View>
    )
}

'Study > React' 카테고리의 다른 글

[React Native] 다른 화면으로 전환하기  (0) 2022.03.09
[React Native] ButtonNavBar 사용하기  (0) 2022.03.09
[React Native] useMemo, useCallback  (0) 2022.03.08
[React Native] useEffect  (0) 2022.03.08
[React Native] 스타일 적용하기  (0) 2022.03.07