Learn/Today I Learn

TIL # 51 < React Native 8 - useEffect vs. useFocusEffect / Dark Mode >

미래개발자 2023. 1. 13. 00:05
728x90

  개발/공부 진행 및 완료상황, 무엇을 더 하면 좋을지

 

React Native 팀프로젝트 진행중..!

 

  오늘 새로 배운 내용

 

useEffect vs. useFocusEffect

useEffect

: 컴포넌트가 마운트(첫 렌더링)되었을 때, dependency가 변경 되었을 때, 언마운트 되었을 때를 감지하여 실행

useEffect(()=>{
	// 한번만 실행
	return () => {
		// 언마운트 시 실행
	}
}, []) // dependency array가 빈배열이면 컴포넌트 마운트 후 한번만 실행

 

useFocusEffect

: 컴포넌트가 화면에 지금 보이는 지(Focus), 안보이는지(Blur)를 감지하여 실행

useFocusEffect(useCallBack(()=>{
	// 컴포넌트가 현재 화면에 있으면 실행: Focus
	return () => {
		// 컴포넌트가 현재 화면에서 벗어나면 실행: Blur
	}
}, []))

 

Dark Mode

// 현재 휴대폰 디스플레이 설정이 다크모드인지 라이트모드인지 확인할 수 있음
const isDark = useColorScheme() === "dark";


import {
  NavigationContainer,
  DarkTheme,
  DefaultTheme,
} from "@react-navigation/native";

// NavigationContainer 속성 중 theme에 리액트 네이티브가 자체적으로 제공하는 Theme 할당
export default function App() {
  const isDark = useColorScheme() === "dark";
  return (
    <NavigationContainer theme={isDark ? DarkTheme : DefaultTheme}>
      <Tabs />
    </NavigationContainer>
  );
}


// styled-components의 ThemeProvider를 활용한 다크모드 컨트롤
// styled-component에서 항상 props.theme에 접근할 수 있다.
export default function App() {
  const isDark = useColorScheme() === "dark";
  return (
    <ThemeProvider theme={isDark ? darkTheme : lightTheme}>
      <NavigationContainer>
        <Root />
      </NavigationContainer>
    </ThemeProvider>
  );
}

// Navigator 또는 Screen 컴포넌트 자체에 Style를 넣을 수도 있다.
export default function Tabs() {
  const isDark = useColorScheme() === "dark";
  return (
    <Tab.Navigator
      sceneContainerStyle={{
        backgroundColor: isDark ? BLACK_COLOR : "white",
      }}
      screenOptions={{
        tabBarStyle: {
          backgroundColor: isDark ? BLACK_COLOR : "white",
        },
        tabBarActiveTintColor: isDark ? YELLOW_COLOR : PURPLE_COLOR,
        headerStyle: { backgroundColor: isDark ? BLACK_COLOR : GRAY_COLOR },
        headerTintColor: isDark ? YELLOW_COLOR : BLACK_COLOR,
      }}
    >
      <Tab.Screen
        options={{
          tabBarBadge: "wow",
          tabBarIcon: ({ focused, color, size }) => {
            console.log(focused, color, size);
            return (
              <MaterialIcons name="local-movies" size={size} color={color} />
            );
          },
        }}
        name="Movies"
        component={Movies}
      />
      <Tab.Screen
        options={{
          tabBarIcon: ({ color, size }) => (
            <Feather name="tv" size={size} color={color} />
          ),
        }}
        name="Tv"
        component={Tv}
      />
      <Tab.Screen
        options={{
          tabBarIcon: ({ color, size }) => {
            return <Feather name="search" size={size} color={color} />;
          },
        }}
        name="Search"
        component={Search}
      />
    </Tab.Navigator>
  );
}
728x90