Home > Mobile >  Using State For React Native Navigation
Using State For React Native Navigation

Time:06-27

I am fairly new to React Native and I am building an app that will be using navigation. I have a solution for navigating screens that seems to work just fine however I do not see many people using this approach. I am using state in a navigation component to render a specific screen(or component).

The main solution(the documented solution) I see is using this package

@react-navigation/native @react-navigation/native-stack

My current solution works like this:

const [screen, setScreen] = useState(0)

const returnScreen = () => {
    switch (screen) {
        case 0:
           return <AccountScreen/>
    }
}

When you click a menu icon, it would change the state to say 1, and render a different screen.

Can someone help me understand why this is a bad approach or an uncommon approach(if it is)? My app will only have 5-7 screens, I am mainly looking to understand why the library is the community approach and if I am missing something.

CodePudding user response:

If you wanted the ability to navigate to other screens to exist outside your menu/drawer you will have to either prop drill your setScreen function or create a context to make it accessible to other components. While this isnt hard to do, it is something that all @react-navigation navigators do without requiring additional code.

If you wanted to enable going to the previous screen, your current navigation code becomes obsolete. Just returning a screen is no longer enough, as you need to track and modify navigation history. So you write more code that you have to test and debug (keep in mind that @react-navigation/stack already does this).

If you are certain that your app will remain small and your navigation features wont increase too much then your approach is completely fine. But if your app will increase in size then you probably will find yourself implementing, testing, and debugging features that have already been implemented, tested, and debugged by the @react-navigation community

  • Related