jpudysz / react-native-unistyles

Level up your React Native StyleSheet

Home Page:https://unistyl.es

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Issue with Theme Persistence When Navigating Back Between Components

ahmadbakhshi opened this issue · comments

Description

Description:
I am encountering an issue in a scenario where navigation occurs among three components, each assigned with a unique theme. The components and their respective themes are as follows:

Component A: Theme A
Component B: Theme B
For each component, upon its initial load, I utilize the UnistylesRuntime.setTheme method to set the corresponding theme. This approach is functioning correctly for the initial load of each component. However, a problem arises when using the router.back method for backward navigation. For example, if I navigate back from Component B to Component A, the theme does not update accordingly and remains set to Theme C, despite the expectation that it should switch to Theme B.

This issue seems occur with backward navigation since previous page is currently loaded. Any insights or solutions to ensure the correct theme is applied when navigating back would be appreciated.

Steps to reproduce

  1. Component A.
const ComponentA = () => {
  // I also tried this
  // React.useLayoutEffect(() => { 
  //   UnistylesRuntime.setTheme(("themeA")
  // }, [])

  // or this
  // React.useEffect(() => { 
  //   UnistylesRuntime.setTheme(("themeA")
  // }, [])

  UnistylesRuntime.setTheme(("themeA")

  return (
    <View>
      <Link href={'componentB'}/>
      <Text>Component A Theme A</Text>
    </View>
  );
};
  1. Component B.
const ComponentB = () => {
  UnistylesRuntime.setTheme(("themeB")

  // expo-router
  const router = useRouter() 

  return (
    <View>
      <Text>Component B Theme B</Text>
      <Button onPress={() =>router.back()}>Go back</Button>
    </View>
  );
};

Snack or a link to a repository (optional)

No response

Unistyles version

2.0.0-alpha.11

React Native version

^0.72.6

Platforms

iOS

Thanks for the report. I think it's because your component A is mounted and going back from component B doesn't re-trigger the useEffect. When it comes to the react-navigation, I was using this hook: https://reactnavigation.org/docs/5.x/use-focus-effect/

As far as I know expo router is built on top of react navigation, so you can use the same approach.

Other approach is to call Unistyles runtime when you go back. Nevertheless you need to call it somewhere.

I hope it will help 🙏