All topics

React Native interview questions

13 questions with answers. 98 open jobs in India ask for React Native.

  1. What is the difference between React Native and React?

    React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications.

    React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood.

    From ReactJS Interview Questions & Answers (MIT)

  2. How to test React Native apps?

    React Native can be tested only in mobile simulators like iOS and Android. You can run the app in your mobile using expo app (https://expo.io) Where it syncs using QR code, your mobile and computer should be in same wireless network.

    From ReactJS Interview Questions & Answers (MIT)

  3. How to do logging in React Native?

    You can use console.log, console.warn, etc. As of React Native v0.29 you can simply run the following to see logs in the console:

    $ react-native log-ios
    $ react-native log-android
    

    From ReactJS Interview Questions & Answers (MIT)

  4. How to debug your React Native?

    Follow the below steps to debug React Native app:

    1. Run your application in the iOS simulator.
    2. Press Command + D and a webpage should open up at http://localhost:8081/debugger-ui.
    3. Enable Pause On Caught Exceptions for a better debugging experience.
    4. Press Command + Option + I to open the Chrome Developer tools, or open it via View -> Developer -> Developer Tools.
    5. You should now be able to debug as you normally would.

    From ReactJS Interview Questions & Answers (MIT)

  5. What is the difference between Hot Reloading and Live Reloading in React Native?

    Live reloading reloads or refreshes the entire app when a file changes. For example, if you were four links deep into your navigation and saved a change, live reloading would restart the app and load the app back to the initial route.

    Hot reloading only refreshes the files that were changed without losing the state of the app. For example, if you were four links deep into your navigation and saved a change to some styling, the state would not change, but the new styles would appear on the page without having to navigate back to the page you are on because you would still be on the same page.

    From Stack Overflow: asked by Raman Choudhary, answered by Nader Dabit (CC BY-SA 3.0)

  6. What are my options for storing data when using React Native? (iOS and Android)

    Here's what I've learned as I determine the best way to move forward with a couple of my current app projects.

    Async Storage (formerly "built-in" to React Native, now moved on its own)

    I use AsyncStorage for an in-production app. Storage stays local to the device, is unencrypted (as mentioned in another answer), goes away if you delete the app, but should be saved as part of your device's backups and persists during upgrades (both native upgrades ala TestFlight and code upgrades via CodePush).

    Conclusion: Local storage; you provide your own sync/backup solution.

    SQLite

    Other projects I have worked on have used sqlite3 for app storage. This gives you an SQL-like experience, with compressible databases that can also be transmitted to and from the device. I have not had any experience with syncing them to a back end, but I imagine various libraries exist. There are RN libraries for connecting to SQLite.

    Data is stored in your traditional database format with databases, tables, keys, indices, etc. all saved to disk in a binary format. Direct access to the data is available via command line or apps that have SQLite drivers.

    Conclusion: Local storage; you supply the sync and backup.

    Firebase

    Firebase offers, among other things, a real time noSQL database along with a JSON document store (like MongoDB) meant for keeping from 1 to n number of clients synchronized. The docs talk about offline persistence, but only for native code (Swift/Obj-C, Java). Google's own JavaScript option ("Web") which is used by React Native does not provide a cached storage option (see 2/18 update below). The library is written with the assumption that a web browser is going to be connecting, and so there will be a semi-persistent connection. You could probably write a local caching mechanism to supplement the Firebase storage calls, or you could write a bridge between the native libraries and React Native.

    Update 2/2018 I have since found React Native Firebase which provides a compatible JavaScript interface to the native iOS and Android libraries (doing what Google probably could/should have done), giving you all the goodies of the native libraries with the bonus of React Native support. With Google's introduction of a JSON document store beside the real-time database, I'm giving Firebase a good second look for some real-time apps I plan to build.

    The real-time database is stored as a JSON-like tree that you can edit on the website and import/export pretty simply.

    Conclusion: With react-native-firebase, RN gets same benefits as Swift and Java. [/update] Scales well for network-connected devices. Low cost for low utilization. Combines nicely with other Google cloud offerings. Data readily visible and editable from their interface.

    Realm

    Update 4/2020 MongoDB has acquired Realm and is planning to combine it with MongoDB Stitch (discussed below). This looks very exciting.

    Update 9/2020 Having used Realm vs. Stitch: Stitch API's essentially allowed a JS app (React Native or web) to talk directly to the Mongo database instead of going through an API server you build yourself.

    Realm was meant to synchronize portions of the database whenever changes were made.

    The combination of the two gets a little confusing. The formerly-known-as-Stitch API's still work like your traditional Mongo query and update calls, whereas the newer Realm stuff attaches to objects in code and handles synchronization all by itself... mostly. I'm still working through the right way to do things in one project, which is using SwiftUI, so it's a bit off-topic. But promising and neat nonetheless.

    Also a real time object store with automagic network synchronization. They tout themselves as "device first" and the demo video shows how the devices handle sporadic or lossy network connectivity.

    Read the rest at the sourceFrom Stack Overflow: asked by Sia, answered by Bryan Scott (CC BY-SA 4.0)

  7. What is the difference between Expo and React Native?

    When you write code in Expo you are writing React Native code. Expo has two main pieces:

    1. Expo CLI (expo-cli): a developer tool for creating projects, viewing logs, opening on your device, publishing, etc.

    2. Expo client: an app on your phone that lets you open your projects while you're working on them, without needing to go through XCode or Android Studio, and also lets other people view them too! And if you publish it through expo-cli, people can access it at any time through the Expo client on Android or on iOS if signed in to the same account it was published with. Lastly, we also make it possible to build standalone apps so people don't have to use the Expo client to open it, and you can distribute to the app store and play store if you like.

    So Expo is a set of tools built on top of React Native. These tools depend on one key belief held at Expo: it's possible to build most apps without ever needing to write native code, provided that you have a comprehensive set of APIs exposed to JavaScript.

    This is important because with React Native you can always drop down to native code. This is incredibly helpful sometimes but it comes at a cost: you need to send people your binaries if you want them to test them, someone on the other side of the world can't just tap a link to open it while you're working on it and you can't just publish it with one click for someone to access it similar to how you would in a browser.

    With Expo, we suggest that try to avoid dropping down to native code, if you can. As I mentioned above, we think that with a comprehensive set of APIs available to JavaScript, this shouldn't be necessary for most apps. So, we aim to provide this comprehensive set of APIs, and then build all of the awesome tooling that can exist in a world where the native runtime is shared.

    However, if you must find that you want to drop down to native, you can use eject and continue using the native APIs that Expo gives you while having the same level of control as you would in any native project.

    Read more about ejecting

    From Stack Overflow: asked by Aurora, answered by brentvatne (CC BY-SA 4.0)

  8. What is the meaning of 'No bundle URL present' in react-native?

    Solve the error No bundle URL present by:

    • Running the following command in your project root directory to delete the iOS build directory, and to kill other React Native sessions (assuming they're running on default port 8081) before re-building:

    rm -rf ios/build/; kill $(lsof -t -i:8081); react-native run-ios

    • Update your React Native workflow to avoid these error occur by combining the above combination of commands into an alias and appending it to your Bash config file .bashrc with this command:

    echo "alias rni=\"kill \$(lsof -t -i:8081); rm -rf ios/build/; react-native run-ios\"" >> ~/.bashrc; source ~/.bashrc

    Now you can run React Native iOS build (without worrying about some of the common red error screens of death appearing) with a simple alias shortcut:

    rni

    From Stack Overflow: asked by Yingch Xue, answered by Luke Schoen (CC BY-SA 3.0)

  9. What is useState() in React?

    React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:

    ...
    const [count, setCounter] = useState(0);
    const [moreStuff, setMoreStuff] = useState(...);
    ...
    const setCount = () => {
        setCounter(count + 1);
        setMoreStuff(...);
        ...
    };
    

    and onClick:

    <button onClick={setCount}>
        Click me
    </button>
    

    Let's quickly explain what is going on in this line:

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

    useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.

    I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail.

    update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

    From Stack Overflow: asked by Hemadri Dasari, answered by Enmanuel Duran (CC BY-SA 4.0)

  10. Is using async componentDidMount() good?

    Let's start by pointing out the differences and determining how it could cause troubles.

    Here is the code of async and "sync" componentDidMount() life-cycle method:

    // This is typescript code
    componentDidMount(): void { /* do something */ }
    async componentDidMount(): Promise<void> {
        /* do something */
        /* You can use "await" here */
    }
    

    By looking at the code, I can point out the following differences:

    1. The async keywords: In typescript, this is merely a code marker. It does 2 things:
      • Force the return type to be Promise<void> instead of void. If you explicitly specify the return type to be non-promise (ex: void), typescript will spit an error at you.
      • Allow you to use await keywords inside the method.
    2. The return type is changed from void to Promise<void>
      • It means you can now do this:
        async someMethod(): Promise<void> { await componentDidMount(); }
    3. You can now use await keyword inside the method and temporarily pause its execution. Like this:

      async componentDidMount(): Promise<void> {
          const users = await axios.get<string>("http://localhost:9001/users");
          const questions = await axios.get<string>("http://localhost:9001/questions");
          // Sleep for 10 seconds
          await new Promise(resolve => { setTimeout(resolve, 10000); });
          // This line of code will be executed after 10+ seconds
          this.setState({users, questions});
          return Promise.resolve();
      }
      

    Now, how could they cause troubles?

    1. The async keyword is absolutely harmless.
    2. I cannot imagine any situation in which you need to make a call to the componentDidMount() method so the return type Promise<void> is harmless too.

      Calling to a method having return type of Promise<void> without await keyword will make no difference from calling one having return type of void.

    3. Since there is no life-cycle methods after componentDidMount() delaying its execution seems pretty safe. But there is a gotcha.

      Let's say, the above this.setState({users, questions}); would be executed after 10 seconds. In the middle of the delaying time, another ...

      this.setState({users: newerUsers, questions: newerQuestions});

      ... were successfully executed and the DOM were updated. The result were visible to users. The clock continued ticking and 10 seconds elapsed. The delayed this.setState(...) would then execute and the DOM would be updated again, that time with old users and old questions. The result would also be visible to users.

    => It is pretty safe (I'm not sure about 100%) to use async with componentDidMount() method. I'm a big fan of it and so far I haven't encountered any issues which give me too much headache.

    From Stack Overflow: asked by TeaNyan, answered by Harry (CC BY-SA 4.0)

  11. Hide keyboard in react-native

    The problem with keyboard not dismissing gets more severe if you have keyboardType='numeric', as there is no way to dismiss it.

    Replacing View with ScrollView is not a correct solution, as if you have multiple textInputs or buttons, tapping on them while the keyboard is up will only dismiss the keyboard.

    Correct way is to encapsulate View with TouchableWithoutFeedback and calling Keyboard.dismiss()

    EDIT: You can now use ScrollView with keyboardShouldPersistTaps='handled' to only dismiss the keyboard when the tap is not handled by the children (ie. tapping on other textInputs or buttons)

    If you have

    <View style={{flex: 1}}>
        <TextInput keyboardType='numeric'/>
    </View>
    

    Change it to

    <ScrollView contentContainerStyle={{flexGrow: 1}}
      keyboardShouldPersistTaps='handled'
    >
      <TextInput keyboardType='numeric'/>
    </ScrollView>
    

    or

    import {Keyboard} from 'react-native'
    <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
        <View style={{flex: 1}}>
            <TextInput keyboardType='numeric'/>
        </View>
    </TouchableWithoutFeedback>
    

    EDIT: You can also create a Higher Order Component to dismiss the keyboard.

    import React from 'react';
    import { TouchableWithoutFeedback, Keyboard, View } from 'react-native';
    const DismissKeyboardHOC = (Comp) => {
      return ({ children, ...props }) => (
        <TouchableWithoutFeedback onPress={Keyboard.dismiss} accessible={false}>
          <Comp {...props}>
            {children}
          </Comp>
        </TouchableWithoutFeedback>
      );
    };
    const DismissKeyboardView = DismissKeyboardHOC(View)
    

    Simply use it like this

    ...
    render() {
        <DismissKeyboardView>
            <TextInput keyboardType='numeric'/>
        </DismissKeyboardView>
    }
    

    NOTE: the accessible={false} is required to make the input form continue to be accessible through VoiceOver. Visually impaired people will thank you!

    From Stack Overflow: asked by TurboFish, answered by Eric Kim (CC BY-SA 4.0)

  12. How can I insert a line break into a <Text> component in React Native?

    This should do it:

    <Text>
    Hi~{"\n"}
    this is a test message.
    </Text>
    

    From Stack Overflow: asked by Curtis, answered by Chris Ghenea (CC BY-SA 4.0)

  13. How to use comments in React?

    Within the render method comments are allowed, but in order to use them within JSX, you have to wrap them in braces and use multi-line style comments.

    <div className="dropdown">
        {/* whenClicked is a property not an event, per se. */}
        <Button whenClicked={this.handleClick} className="btn-default" title={this.props.title} subTitleClassName="caret"></Button>
        <UnorderedList />
    </div>
    

    You can read more about how comments work in JSX here.

    From Stack Overflow: asked by user1177440, answered by Henrik Andersson (CC BY-SA 4.0)

Related topics

Where these questions come from

Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.