React Native Interview Questions

What is React Native?

React Native is the next generation of React – a Javascript code library developed by Facebook and Instagram, which was released on Github in 2013. 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.

Facebook opened up React in 2013 and has been using its proprietary React Native code for iOS app development for over a year.

Why open source?

“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.

How did Facebook write React Native for Android?

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.

Airbnb, Box, Facebook, GitHub, Google, Instagram, LinkedIn, Microsoft, Pinterest, Pixar Animation Studios, Twitter, Uber, and WhatsApp all use React code.

What’s the Challenges with React Native?

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.

Advantages of React Native?

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.

Handling Multiple Platforms?

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.

Are all React components usable in React Native?

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.

Passing functions between components in React and React Native?

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.

Difference between React Native and NativeScript, which one do you prefer and why?

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.

Are there any disadvantages to using React Native for mobile development?

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.

What is the difference between using constructor vs getInitialState in React / React Native?

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 */ };
},
});

what is a prop?

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.

Re-Render on Changes?

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.

Each of the prop and state change triggers a complete re-render of the component.

What is the concept of “single source of tWhat is the concept of “single source of truth” in Redux?

The state of your whole application is stored in an object tree within a single store. This makes it easy to create universal apps, as the state from the server can be serialized and hybridized into the client with no extra coding effort. A single state tree also makes it easier to debug or introspect an application; it also enables persisting the app’s state in development, for a faster development cycle.

How is it different from MVC and Flux?

In classical widely known MVC architecture, there is a clear separation between data (model), presentation (view) and logic (controller). There is one issue with this, especially in large-scale applications: The flow of data is bidirectional. This means that one change (a user input or API response) can affect the state of an application in many places in the code — for example, two-way data binding. That can be hard to maintain and debug.

Flux is very similar to Redux. The main difference is that Flux has multiple stores that change the state of the application, and it broadcasts these changes as events. Components can subscribe to these events to sync with the current state. Redux doesn’t have a dispatcher, which in Flux is used to broadcast payloads to registered callbacks. Another difference in Flux is that many varieties are available, and that creates some confusion and inconsistency.

What are “actions” in Redux?

In a nutshell, actions are events. Actions send data from the application (user interactions, internal events such as API calls, and form submissions) to the store. The store gets information only from actions. Internal actions are simple JavaScript objects that have a type property (usually constant), describing the type of action and payload of information being sent to the store.

{

type: LOGIN_FORM_SUBMIT,

payload: {username: ‘alex’, password: ‘123456’

}
}

Actions are created with action creators. That sounds obvious, I know. They are just functions that return actions.function authUser(form)

{
return

{
type: LOGIN_FORM_SUBMIT,

payload: form

}
}

Calling actions anywhere in the app, then, is very easy. Use the dispatch method, like so:dispatch(authUser(form));

What is the role of reducers in Redux?

In Redux, reducers are functions (pure) that take the current state of the application and an action and then return a new state. Understanding how reducers work is important because they perform most of the work. Here is a very simple reducer that takes the current state and an action as arguments and then returns the next state:function handleAuth(state, action)

{
return _.assign({}, state,

{
auth: action.payload
});
}

For more complex apps, using the combineReducers() utility provided by Redux is possible (indeed, recommended). It combines all of the reducers in the app into a single index reducer. Every reducer is responsible for its own part of the app’s state, and the state parameter is different for every reducer. The combineReducers() utility makes the file structure much easier to maintain.

If an object (state) changes only some values, Redux creates a new object, the values that didn’t change will refer to the old object and only new values will be created. That’s great for performance. To make it even more efficient you can add Immutable.js.const rootReducer = combineReducers({
handleAuth: handleAuth,
editProfile: editProfile,
changePassword: changePassword
});

What is ‘Store’ in Redux?

Store is the object that holds the application state and provides a few helper methods to access the state, dispatch actions and register listeners. The entire state is represented by a single store. Any action returns a new state via reducers. That makes Redux very simple and predictable.import { createStore } from ‘redux’;
let store = createStore(rootReducer);
let authInfo = {username: ‘alex’, password: ‘123456’};
store.dispatch(authUser(authInfo));

What Happens When You Call Setstate?

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.

What’s The Difference Between An Element And A Component In React?

Simply put, a React element describes what you want to see on the screen. Not so simply put, a React element is an object representation of some UI.

A React component is a function or a class which optionally accepts input and returns a React element (typically via JSX which gets transpiled to a createElement invocation).

When Would You Use A Class Component Over A Functional Component?

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

What Are Refs In React And Why Are They Important?

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>
)
}

What Are Keys In React And Why Are They Important?

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 Which Lifecycle Event Do You Make Ajax Requests And Why?

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.

What Does Should component update Do And Why Is It Important?

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.

How Do You Tell React To Build In Production Mode And What Will That Do?

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.

Summary
Review Date
Reviewed Item
Nice Interview questions for react native Keep posting it.
Author Rating
51star1star1star1star1star