Using useState props in React Native navigation screens with React Navigation

I'm currently working on my first React Native app with react navigation after previously having a background in web react development.

In the past, I typically used useState for managing state. For instance, rendering a list of components based on data retrieved from a database query (such as a Friend List feature) or handling multi-step user sign up processes where each page contributes to the overall state that is then submitted via a post request.

However, it seems like this straightforward approach doesn't work quite the same in React Native. With React Navigation, every screen component is enclosed within a <Stack.Screen> component. How can I pass props to update parent component states? Is Redux necessary for achieving this?

To better explain how I managed this process in React before, let's look at an example involving a 5-step sign up flow:

The user lands on the signup page and fills out information on url/page1. After clicking next, the button triggers setState received from its parent to update the app.state. Then, it transitions to url/page2.

On url/page2, users input their address and continue by hitting next, updating the state and progressing to the subsequent step, and so forth.

Each page adds more details to the state until the final "submit" action aggregates all data and sends it through a POST request to the backend.

Within my React Native app.js, the structure looks similar but with different screens:

<NavigationContainer>
    <Stack.Navigator initialRouteName = "TempHome">
        <Stack.Screen name="TempHome" component={TempHome} />
        ...
    </Stack.Navigator>
</NavigationContainer>

With each screen transitioning to the next using

const ProfileSetupF = () => navigation.navigate('ProfileSetupF')

How do I implement state props management within this context without consolidating all setup screens into a single component or stack.Screen? I want users to utilize the back button and experience smooth transitions when moving between screens. Some suggest utilizing Redux for this purpose. Any suggestions or guidance would be greatly appreciated.

Answer №1

To effectively handle this scenario, the recommended approach is to utilize the context API. You can learn more about it here: https://reactjs.org/docs/context.html

It's important to note that there is no requirement for the context to be global. You can selectively wrap components, such as authentication components, with the context provider.

An ideal setup would involve creating an AuthenticationContext like below:

const AuthContext = createContext();
  
export const AuthProvider = (props) => {
    const [user, setUser] = useState(null);
    
    const login = async () => {
        // LOGIN FUNCTIONS
        login().then(userDocument => setUser(userDocument))
    }

    return (
        <AuthContext.Provider
            value={{
                user,
                login: login
            }}
        >
            {props.children}
        </AuthContext.Provider>
    );
};

You can then wrap your NavigationProvider with the AuthProvider and check if a user is logged in using the following snippet:

const {user} = useContext(AuthContext)

A more efficient approach would be to dynamically generate a navigator based on the AuthContext, as demonstrated below:

const AppNavigator = () = {
  const {user} = useContext(AuthContext);

  return (
<>
        {!user ? <Stack.Navigator initialRouteName = "Auth">
          <Stack.Screen name="TempHome" component={TempHome} />
          <Stack.Screen name="Welcome" component={Welcome} />
          <Stack.Screen name="LogIn" component={LogIn} />
          <Stack.Screen name="SignUp" component={SignUp} />
        </Stack.Navigator>
       :
       <Stack.Navigator initialRouteName = "TemHome">
          <Stack.Screen name="ProfileSetupA" component={ProfileSetupA} />
          <Stack.Screen name="ProfileSetupB" component={ProfileSetupB} />
          <Stack.Screen name="ProfileSetupC" component={ProfileSetupC} />
          <Stack.Screen name="ProfileSetupD" component={ProfileSetupD} />
          <Stack.Screen name="ProfileSetupE" component={ProfileSetupE} />
          <Stack.Screen name="ProfileSetupF" component={ProfileSetupF} />
          <Stack.Screen name="ProfileSetupG" component={ProfileSetupG}/>
          <Stack.Screen name="ProfileSetupH" component={ProfileSetupH}/>
          <Stack.Screen name="PetProfileHome" component={PetProfileHome} />
          <Stack.Screen name="PetProfileScheduledActivities" component={PetProfileScheduledActivities} />
          <Stack.Screen name="PetProfileAccount" component={PetProfileAccount} />
          <Stack.Screen name="PetProfileTraits" component={PetProfileTraits} />
          <Stack.Screen name="PetProfileInvitation" component={PetProfileInvitation} />

          <Stack.Screen name="Notification" component={Notification} />
          <Stack.Screen name="NetworkExample" component={Network} />
          <Stack.Screen name="MapExample" component={MapExample} />
          <Stack.Screen name="ShareExample" component={ShareExample} />

        </Stack.Navigator>
</>
  )
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create a custom definition for the useSelector function within a separate TypeScript file in a React

Question: Is it possible to define a type like <TRootState, string> in an external file and use it directly inside multiple Component files? External file: export type TUser = <TRootState, string> // This method does not work Component's ...

Using environmental variables in Nuxt 2 or Nuxt 3 - a step-by-step guide

I have an .env file located in the root of my project. In my nuxt config, I am using variables to configure ReCaptcha as shown below: import dotenv from 'dotenv' dotenv.config() export default { modules: [ ['@nuxtjs/recaptcha&ap ...

Interested in integrating server side JavaScript with your Android application?

Running a simple web page on a Raspberry Pi to toggle the board's LED with the click of a button. The button triggers a JavaScript function that controls the LED. Now, I want to be able to call this script from a button in an Android application... B ...

Examining whether an ajax call was not initiated within an Angular application

Is there a way to verify that an ajax request has not been made using Angular's $httpBackend? I attempted to use verifyNoOutstandingRequest() but it doesn't seem to be triggering test failures in version 1.1.5. Here is more information about the ...

Utilizing Odometer to pass a variable to jQuery

I'm interested in incorporating a jQuery odometer into a master page to display dynamic information. I found a helpful resource for this at this link. To achieve this, I need to fetch data from a SQL Server database using C# and then pass it to the J ...

Enhance user experience with jQuery UI sortable and the ability to edit content in real

I am facing an issue with jquery sortable and contenteditable. The problem arises when I try to use jquery sortable along with contenteditable, as the contenteditable feature stops working. After searching on Stack Overflow, I found a solution. However, up ...

Guide on creating uniform heights and widths for images with varying dimensions utilizing CSS (and percentage values)

Is there a way to ensure that all images maintain the same height and width using CSS percentages, rather than set pixel values? I'm working on displaying images in circles, where most are uniform in size but a few outliers distort the shape. The wide ...

"I'm encountering an issue with Passport.js where req.isAuthenticated is throwing an error as not

Recently I started working with node and express, along with passport.js for building an authentication feature. However, I encountered an issue while using a middleware function called "checkNotAuthenticated" in my routes. The error message I received was ...

Troubleshooting problem with AngularJS and jQuery plugin when using links with # navigation

I have integrated a specific jquery plugin into my angularjs single page application. The primary block can be found in the following menu: http://localhost:81/website/#/portfolio This menu contains the following code block: <li> <a href=" ...

Is it possible for a search box selection toggle to reveal a hidden information box underneath it containing all the compiled data?

Improve the user experience on my website by implementing a search feature for US states and Canadian territories. When visitors type in their selection, I want them to be able to click on an icon that will reveal relevant information about that choice. T ...

Internal styles are effective, while external styles seem to be less efficient

For some reason, internal CSS is working fine, but external CSS just won't cooperate. I even tried using the code !important, but it's like it doesn't understand. I'm trying to incorporate a gallery into my website, but I've hit a ...

The authorization process for uploading data to Azure Data Lake Gen2

Currently, I am working on generating a Shared Access Signature (SAS) client-side within my Node.js application. The primary goal is to allow users to directly upload files to my Azure Data Lake Gen2 Blob Storage container without streaming them through th ...

Basic click event triggered every second click in JavaScript and HTML

onclick="HandleAction(\'playnow\');HandleAction(\'stop\');" This element performs two functions simultaneously. However, it only executes the actions \playnow\ and then \stop\ immediately after. ...

Javascript's ReferenceError occasionally acts inconsistently when using Firefox's scratchpad

While delving into the world of Javascript for learning purposes, I encountered an unexpected behavior. Let's explore this scenario: function hello(name) { let greet = 'Hello ' alert(greet + name) } hello('world') alert(gree ...

Translating coordinates into their corresponding location on the chart

I'm currently working with a dataset containing information about an area in Western Europe. I am trying to convert coordinates into values within this table, facing a challenge similar to the one described in this query. However, I lack experience in ...

Can you identify the target of the term "this" in the upcoming JavaScript code?

DISCLAIMER: I am inquiring about a specific instance of this, not its general purpose. Please refrain from quick Google responses or copied answers (: The code snippet below demonstrates JavaScript/jQuery: var req = {}; function getData() { var from ...

Querying and Retrieving a List of Nested Documents in MongoDB

I have multiple solutions, each of which may contain various projects. To represent this relationship, I opted for embedding the projects within the solution document. For example: [{ _id: "1", solutionTitle: "Some Sample Solution", p ...

Automatically close the popup each time it is displayed (using jQuery/JavaScript)

I am having issues with auto-closing my popup each time I open it. The current code I have only closes the popup the first time, requiring me to refresh the browser in order to auto-close it again. Can someone please assist me in writing a new code that ...

Instructions for removing a class using the onclick event in JavaScript

Is there a way to make it so that pressing a button will display a specific class, and if another button is pressed, the previous class is removed and a new one is shown? Thank you for your assistance. function myFunction() { document.getElementById ...

Creating a visual representation of data using Google Charts to display a stacked bar chart

I wrote a script to display a stacked Google chart using JSON data stored on the wwwroot directory - <html> <head> <title>DevOps Monitoring Application</title> <link rel="icon" type="image/png" hr ...