Top 30 React Native Interview Questions You Must Prepare 19.Mar.2024

React JS for the web is fantastic. But when it comes to React Native - i felt i was boxed or caged to Reacts way of creating the views and constructing the screen there after.

With NativeScript that's not the case. The UI definition follows XML syntax. I know XML so easy to follow. When it comes to application logic - it allows ES5, TypeScript - again which i already know so i can reuse my skill. You use a subset of CSS to style your app. Again big plus point here - if you know CSS3, NS allows you to use most of the basic rule sets to style your app. Basically NS is all about open standards - you don't have to learn anything new. you use what you all ready know.

Having played around with it for a few weeks, I've found React Native to be fairly buggy. I don't think it's anywhere near production ready. A lot of features are currently still missing, for example, pin annotations for maps. Being that it's open source, there's nothing stopping you from building the feature yourself, but if you're trying to get something created quickly / for production, you're better off using developing directly for iOS or Android.

ReactJs is a JavaScript Library used for developing apps in HTML5 using JavaScript as the developing language and React Native is used to develop native mobile apps using JavaScript as the development language.

Yes, we can use Native code alongside JavaScript to get our tasks done, so the limitations in previous such platforms such as Titanium will be no more.

React Native is the next generation of React - a Javascript code library developed by Facebook and Instagram, which was released on Github in 201@Native app creation means writing apps for a specific operating system.

React Native helps developers reuse code across the web and on mobile. Engineers won't have to build the same app for iOS and for Android from scratch - reusing the code across each operating system.

Android and iOS have very different codebases and startups and businesses often struggle to hire - or afford- engineers for both. Now just one developer can write across different mobile operating systems.

React Native gracefully handles multiple platforms. The vast majority of the React Native APIs are cross-platform, so you just need to write one React Native component, and it will work seamlessly on both iOS and Android. Facebook claims that their Ad Manager application has 87% code reuse across the two platforms, and I wrote a flashcard app without any platform-specific code at all.

If you do want to write platform-specific code -- due to different interaction guidelines on iOS and Android, for instance, or because you want to take advantage of a platform-specific API -- that's easy, too. React Native allows you to specify platform-specific versions of each component, which you can then integrate into the rest of your React Native application.

A good analogy to define "what is a prop?" has been likened to the real life situation of when a person moves from one home to another. A moving van pulls up and all the contents of the home are loaded in the van and it drives off to be unloaded into the new house. The house is the scenery. The scenery includes the actual walls, floors, ceilings, doors- the architecture of the house. This does not move. It is stationary and permanent. The items boxed up, covered in pads, and carried out to the moving van when a person is changing residences would all be considered the props.

The base setup for building with Android and iOS are the same, but once you start getting into the development of your app, there are a few differences. From what I've experienced, we can probably bet on using about 80% of our code cross platform. I've heard of others using up to 90%, and I've normally heard the number being around 85%.

To use the code cross platform, you would just copy the code from your .ios.js or .android.js file, and copy it into the other. As long as there are not platform specific components, it should work.

Also:

There are a few modules that were build specifically for iOS, and there are a few that were specifically built for Android, and some of them work cross platform. For example, ActivityIndicatorIOS is an iOS styled element, but if you look in the component itself, you will see both ActivityIndicatorIOS.android.js and ActivityIndicatorIOS.ios.js, so it should at least work cross platform, but UI will probably not be what you would be looking for in Android.

If you install any plugins that need to access any native functionality, for example using a custom font, you will need to do a bit of work separately (on each platform) to get them working for each platform and it will not work cross platform.

Bridging will be entirely different for each platform, though this may not be something you would even have to worry about unless you needed to do something that React Native does not support out of the box. To build in IOS, you will need a Mac and Xcode. To build in Android, you will need the android SDK and some type of emulator (I use Genymotion). But keep in mind that as of now, you can't develop iOS on a Windows machine unless you use something like ExponentJS, but if you have a Mac, you can develop cross platform.

The first thing React will do when setState is called is merge the object you passed into setState into the current state of the component. This will kick off a process called reconciliation. The end goal of reconciliation is to, in the most efficient way possible, update the UI based on this new state.

To do this, React will construct a new tree of React elements (which you can think of as an object representation of your UI). Once it has this tree, in order to figure out how the UI should change in response to the new state, React will diff this new tree against the previous element tree. By doing this, React will then know the exact changes which occurred, and by knowing exactly what changes occurred, will able to minimize its footprint on the UI by only making updates where absolutely necessary.

"If we work together in the open, we can advance the state of technology together," Facebook said in a blog post yesterday evening.

Altruism aside, opting to open source code is a tricky decision. Keeping a businesses infrastructure under-wraps has commercial advantages, especially when your technology is your business model.

But the developer community is loyal to those who open up. Web engineers across the world are quick to point out a bug in the code for free.

Developing open source projects helps keep Facebook one of the most coveted companies to work for. Developers want a challenge, and a sense of giving back - and Facebook wants a large pool of talented engineers to pick its employees from.

Plus, it saves on training. If every engineer Facebook hires already knows how to write in React Native, they have a running start.

Facebook has a culture of maturing its development. Over ten years' it has scaled to serve one billion users, thousands of developers and three major platforms - iOS, Android and Web.

It's a considerable development from when the fledgling startup copied Facebook code on Harvard University's server for releases and,"poke on it to see if it was still working every day at 10am," mobile engineering manager Bryan O'Sullivan joked earlier this year.

If your component has state or a lifecycle method(s), use a Class component. Otherwise, use a Functional component.

Refs are an escape hatch which allow you to get direct access to a DOM element or an instance of a component. In order to use them you add a ref attribute to your component whose value is a callback function which will receive the underlying DOM element or the mounted instance of the component as its first argument.

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

Above notice that our input field has a ref attribute whose value is a function. That function receives the actual DOM element of input which we then put on the instance in order to have access to it inside of the handleSubmit function.

It’s often misconstrued that you need to use a class component in order to use refs, but refs can also be used with functional components by leveraging closures in JavaScript.

function CustomForm ({handleSubmit}) {
  let inputElement
  return (
    <form onSubmit={() => handleSubmit(inputElement.value)}>
      <input
        type='text'
        ref={(input) => inputElement = input} />
      <button type='submit'>Submit</button>
    </form>
  )
}

React Native compiles a real mobile and is engineered for high performance, a good example of a high performance app is Facebook IOS app; it uses React Native and IOS users have a pretty good idea of how smoothly the Facebook app works on IOS devices.

Typically you’d use Webpack’s DefinePlugin method to set NODE_ENV to production. This will strip out things like propType validation and extra warnings. On top of that, it’s also a good idea to minify your code because React uses Uglify’s dead-code elimination to strip out development only code and comments, which will drastically reduce the size of your bundle.

The fact that React Native actually renders using its host platform's standard rendering APIs enables it to stand out frommost existing methods of cross-platform application developement ,like Cordova or Ionic. Existing methods of writing mobile applications using combinations of JavaScript,HTML,and CSS typically render using webviews.While this approach can work, it also comes with drawbacks,especially around performance.

Additionally,they do not usually have access to the host platform's set of native UI elements.When these frame works do try to mimic native UI elements,the results usually "feel" just a little off; reverse-engineering all the fine details of things like animations takes an enormous amount of effort,and they can quickly become out of date.

In contrast, Reactive Native actually translates your markup to real,native UI elements,leveraging existing means of rendering views of whatever platform you are working with. Additionally,React works separately from the main UI thread,so your application can maintain high performance without sacrificing capability.The update cycle in React Native is the same as in React :when props or state change,React Native re-renders the views.The major differnce between React Native and React in the browser is that React Native does this by leveraging the UI libraries of its host platform, rather than using HTML and CSS markup.

For developers accustomed to working on the Web with React,this means you can write mobile apps with performance and look and feel of anative application,while using familiar tools. React Native also represents an improvement over normal mobile development in two other areas:the developer experience and cross-platform development potential.

createElement is what JSX gets transpiled to and is what React uses to create React Elements (object representations of some UI). cloneElement is used in order to clone an element and pass it new props.

The first cross-platform React Native app - ads manager - was developed by the London-based dev team, who were in the US to announce the Android release yesterday evening. Ads manager lets businesses that advertise on the social network manage their accounts and create new adverts.

React Native has only recently been proven in production and building a new app based on the framework carried some risk.

Three product engineers familiar with React set about to create an app for Android and predicted problems with the logic necessary to understand differing time zones, date formats, currencies and ad formats across the world.

This business logic was already written in JavaScript, and the team knew it wouldn't be efficient to build it all again in Objective-C to do it again in Java for Android.

Now this project has been released on Github, developers can use a single workflow to develop for iOS and Android. This means you can use the same editor and propagate it to both the iOS simulator and Android emulator at the same time.

Keys are what help React keep track of what items have changed, been added, or been removed from a list.

render () {
  return (
    <ul>
      {this.state.todoItems.map(({task, uid}) => {
        return <li key={uid}>{task}</li>
      })}
    </ul>
  )
}

It’s important that each key be unique among siblings. We’ve talked a few times already about reconciliation and part of this reconciliation process is performing a diff of a new element tree with the most previous one. Keys make this process more efficient when dealing with lists because React can use the key on a child element to quickly know if an element is new or if it was just moved when comparing trees. And not only do keys make this process more efficient, but without keys, React can’t know which local state corresponds to which item on move. So never neglect keys when mapping.

In order to solve cross browser compatibility issues, your event handlers in React will be passed instances of SyntheticEvent, which is React’s cross-browser wrapper around the browser’s native event. These synthetic events have the same interface as native events you’re used to, except they work identically across all browsers.

What’s mildly interesting is that React doesn’t actually attach events to the child nodes themselves. React will listen to all events at the top level using a single event listener. This is good for performance and it also means that React doesn’t need to worry about keeping track of event listeners when updating the DOM.

A large part of React is this idea of having components control and manage their own state. What happens when we throw native HTML form elements (input, select, textarea, etc) into the mix? Should we have React be the “single source of truth” like we’re used to doing with React or should we allow that form data to live in the DOM like we’re used to typically doing with HTML form elements? These two questions are at the heart of controlled vs uncontrolled components.

A controlled component is a component where React is in control and is the single source of truth for the form data. As you can see below, usernamedoesn’t live in the DOM but instead lives in our component state. Whenever we want to update username, we call setState as we’re used to.

class ControlledForm extends Component {
  state = {
    username: ''
  }
  updateUsername = (e) => {
    this.setState({
      username: e.target.value,
    })
  }
  handleSubmit = () => {}
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          value={this.state.username}
          onChange={this.updateUsername} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

An uncontrolled component is where your form data is handled by the DOM, instead of inside your React component.

You use refs to accomplish this.

class UnControlledForm extends Component {
  handleSubmit = () => {
    console.log("Input Value: ", this.input.value)
  }
  render () {
    return (
      <form onSubmit={this.handleSubmit}>
        <input
          type='text'
          ref={(input) => this.input = input} />
        <button type='submit'>Submit</button>
      </form>
    )
  }
}

Though uncontrolled components are typically easier to implement since you just grab the value from the DOM using refs, it’s typically recommended that you favor controlled components over uncontrolled components. The main reasons for this are that controlled components support instant field validation, allow you to conditionally disable/enable buttons, enforce input formats, and are more “the React way”.

Yes, React Native Compiles a native mobile app using native app components. It’s neither a Hybrid Mobile app that uses WebView to run the HTML5 app or a mobile web app. React Native builds a real mobile app that’s indistinguishable from an app built using Objective-C or Java.

Yes, we use the same code base for Android and IOS and React take cares of the native components translations. For example: A React Native ScrollView uses native UiScrollView on IOS and ScrollView on Android.

In addition to props, components can also have an internal state. The most prominent example of that behavior would be a click counter that updates its value when a button is pressed. The number of clicks itself would be saved in the state.

The two approaches are not interchangeable. You should initialize state in the constructor when using ES6 classes, and define the getInitialState method when using React.createClass.

class MyComponent extends React.Component {
constructor(props) {
super(props);
this.state = { /* initial state */ };
}
}

is equivalent to

var MyComponent = React.createClass({
getInitialState() {
return { /* initial state */ };
},
});

Working across separate iOS and Android codebases is challenging.

"When we were building the app, Facebook used this model, and all our build automation and developer processes were set up around it. However, it doesn't work well for a product that, for the most part, has a single shared JavaScript codebase," wrote Daniel Witte and Philipp von Weitershausen, engineers at Facebook in a blog yesterday.

Developers who often struggle to figure out where the master code exists and whether bugs have been fixed in all platforms may want to hold out for when Facebook opens up its unified repository. It is moving all of its code from Git to Mercurial, and will be one of the largest codebases of its kind.

Google is another web giant that understands the power of open source, recently committing to OpenStack and creating an enitrely open source container management project, Kubernetes. The project seems at odds with its own Google cloud business, but again, it knows that the benefits outweigh any loss of Google cloud customers.

A callback function which will be invoked when setState has finished and the component is re-rendered.

Something that’s not spoken of a lot is that setState is asynchronous, which is why it takes in a second callback function. Typically it’s best to use another lifecycle method rather than relying on this callback function, but it’s good to know it exists.

this.setState(
  { username: 'tylermcginnis33' },
  () => console.log('setState has finished and the component has re-rendered.')
)

AJAX requests should go in the componentDidMount lifecycle event.

There are a few reasons for this,

  • Fiber, the next implementation of React’s reconciliation algorithm, will have the ability to start and stop rendering as needed for performance benefits. One of the trade-offs of this is that componentWillMount, the other lifecycle event where it might make sense to make an AJAX request, will be “non-deterministic”. What this means is that React may start calling componentWillMount at various times whenever it feels like it needs to. This would obviously be a bad formula for AJAX requests.
  • You can’t guarantee the AJAX request won’t resolve before the component mounts. If it did, that would mean that you’d be trying to setState on an unmounted component, which not only won’t work, but React will yell at you for. Doing AJAX in componentDidMount will guarantee that there’s a component to update.

Above we talked about reconciliation and what React does when setState is called. What shouldComponentUpdate does is it’s a lifecycle method that allows us to opt out of this reconciliation process for certain components (and their child components). Why would we ever want to do this? As mentioned above, “The end goal of reconciliation is to, in the most efficient way possible, update the UI based on new state”. If we know that a certain section of our UI isn’t going to change, there’s no reason to have React go through the trouble of trying to figure out if it should. By returning false from shouldComponentUpdate, React will assume that the current component, and all its child components, will stay the same as they currently are.

I would stay away from such passing functions between components. I always use Flux architecture with ReactJs and React Native.

Keep components just to render stuff by properties and sending new actions.

You have hard dependency between components. This stuff does not scale. It will be hard to maintaine such code.

What i personally do is just write actions, stores, dispatcher and don't use any dependency on stuff like redux, because React Native is envolving rapidly and you never know if your dependencies will do it at same speed.

Web React components use DOM elements to display (ex. div, h1, table, etc) but these are not supported by React Native. You'll need to find libraries/components made specifically for React Native.

I doubt there are components that supports both, thus it should be fairly easy to figure out if it's made for React Native or not. As of now, if the creator does not specifically say that they made for React Native, it probably does not work on React Native.