Category: React Native Interview Question

https://cdn3d.iconscout.com/3d/premium/thumb/interview-question-3d-icon-download-in-png-blend-fbx-gltf-file-formats–interviewer-hr-manager-pack-business-icons-9684875.png?f=webp

  • How do you handle real-time updates in a React Native app? 

    Handling real-time updates involves: 

    • WebSockets: Establish a WebSocket connection for continuous data flow. 
    • FirebaseUse Firebase for real-time database synchronization and updates. 
    • Polling: Implement polling for periodic data fetching. 

    These methods ensure the app stays updated with the latest data, providing a dynamic user experience. 

  • How do you manage app state using Redux Thunk or Redux Saga?  

    Managing app state can be done using: 

    • Redux Thunk: 
    • Allows writing action creators that return a function instead of an action. 
    • Suitable for simple asynchronous logic like API calls. 
    • Redux Saga: 
    • Uses generator functions to handle side effects more efficiently. 
    • Ideal for complex asynchronous workflows, allowing better control over execution flow. 

    Both tools enhance state management in large applications by handling asynchronous actions effectively. 

  • How do you ensure the security of a React Native application? 

    Ensuring security involves several practices: 

    • Secure Storage: Use secure storage solutions for sensitive data. 
    • Input Validation: Validate and sanitize all user inputs to prevent injection attacks. 
    • Authentication and AuthorizationImplement robust authentication mechanisms and restrict access to authorized users. 
    • Dependency Management: Keep dependencies updated to avoid known vulnerabilities. 

    These practices help protect the application from common security threats and ensure data integrity. 

  • What is the purpose of code splitting, and how do you achieve it in React Native? 

    Code splitting improves performance by loading only the necessary code for the current screen. It can be achieved using: 

    • Dynamic Imports: Load components or modules only when needed. 
    • React.lazy and Suspense: Split code and load it asynchronously, reducing the initial bundle size. 

    Code splitting helps optimize load times and enhances the app’s performance by avoiding unnecessary code loading. 

  • How do you handle offline functionality in a React Native app?

    Handling offline functionality involves: 

    • Data Storage: Use libraries like Redux Persist or AsyncStorage to store data locally. 
    • Synchronization: Sync local data with the server when the connection is restored. 
    • Fallback UI: Provide fallback UI elements to inform users about the offline status. 

    These techniques ensure the app remains functional and provides a smooth user experience even without an internet connection. 

  • How do you create a basic button in React Native?

    React native provides Button component which displays platform specific button. Following example shows how we create a platform-specific default button in React native. Platform-specific button means that the look and feel on a button will depend on whether the application is running on IOS or Android. Button component exposes two main props: title and onPress. Title props are used to display text on the button. onPress props is a callback which is invoked when the user presses the button. This is very much similar to the click event on a web browser. We can’t style the Button component provided by React native.

    Basic button in React Native
    import React from 'react';
    import { View, Alert, Button, StyleSheet } from "react-native";
    
    const SimpleButton = (props) => {
        return ( <Button style={styles.button} onPress={() => Alert.alert("You pressed button")} title="Click Me"/> );
    };
    
    const styles = StyleSheet.create({
        button: {
            padding: 5,
            color: '#000'
        }
    });
    
    export default SimpleButton;

    Above example will show platform specific alert when the user presses the button. Alert is the component provided by React native framework to show platform specific modal. As I mentioned above that we can’t style Button component of React native, we can try this by changing the text colour of a button or changing the padding via style props but it won’t change the appearance of the button.

  • How do you create basic text input to React Native?

    TextInput is provided by React native framework to implement simple text input control. Text input is one of the very basic controls of UI. Whether it is auto-complete, form, text input is a must used control in UI of application. TextInput component accepts placeholder value as props. When a user starts changing the text then the onChangeText event is triggered and when the user is done editing and hit return button, onSubmitEditing props will get invoked. TextInput component can be styled by setting style props to the component. Here is an example of the implementation of simple text input in React native:

     basic text input to React Native
    import React from 'react';
    import { View, Text, TextInput, StyleSheet } from "react-native";
    
    class SimpleTextInput extends React.Component {
        constructor(props) {
            super(props);
            this.state = { text: '', isSubmitted: false };
        }
        handleChangeText = (text) => {
            this.setState({ text, isSubmitted: false });
        }
        handleSubmitText = () => {
            this.setState({ isSubmitted: true });
        }
        render() {
            const { text, isSubmitted } = this.state;
            return (
                <View style={styles.container}>
                    <TextInput
                        style={styles.input}
                        placeholder={'Type here...'}
                        onChangeText={this.handleChangeText}
                        onSubmitEditing={this.handleSubmitText}/>
                    <Text style={styles.text}>{isSubmitted?User has typed: ${text}:'User is typing'}</Text>
                </View>
            );
        }
    }
    const styles = StyleSheet.create({
        container: {
            alignSelf: 'stretch',
            margin: 10,
            padding: 10,
            borderColor: '#ccc',
            borderWidth: 1,
            borderRadius: 5,
            backgroundColor: '#eaf7fd'
        },
        text: {
            fontSize: 14,
            fontWeight: 'bold',
            color: '#015169'
        },
        input: {
            height: 40
        }
    });
    
    export default SimpleTextInput;

    In the above example: we have a TextInput component whose value is controlled by the state. Which means our TextInput in above example is a controlled component. Once the user starts typing we update the state with an onChangeText method. Once the user submits the value, we display the value user has typed in the text box.

  • Give a quick overview of the life cycle of a React component?

    Below image summarise the lifecycle methods exposed by react component and the order in which lifecycle methods are being called by React.

    life cycle of a React component

    React 16 was a major release for ReactJS. With this version react has marked some of the lifecycle methods like componentWillRecieveProps, ComponentWillUpdate as deprecated. In a later release of React, the framework will be removing these methods. In place of deprecated methods, they added a few new lifecycle methods. The above picture shows the lifecycle method of a component. We can divide the lifecycle methods of the component into three categories.

    • Mounting: This includes the beginning phase of the component. The first constructor of the component gets invoked. Constructor receives props as an argument from the parent component. Constructor is the place where we define an initial state of a component. After constructor and before render, lifecycle method getDrivedStateFromProps is invoked, it returns the state object or null to avoid the render. Then Render method is invoked which renders the JSX. Then at the end, componentDidMount is invoked.
    • Updating: A component gets an update via a change in state or change in props. In both of these cases, the getDrivedStateFromProps method is invoked first where we get props and state as an argument and returns updated state. Then shouldComponentUpdate methods are invoked. If this method returns true then the only component gets the update otherwise component update is aborted. Then render method is called and after this getSnapshotBeforeUpdate is called. In the end, the componentDidUpdate method is called
    • Unmounting: componentWillUnmount lifecycle method is invoked before the unmounting of the component takes place.
  • What is the difference between a functional component and a class-based component?

    Though we can implement in both functional and class-based way, there are few fundamental differences between the two of them:

    1. Functional component can’t have stated ( before React hooks era ). It renders component only based on props passed. A class-based component can have a local state which can be helpful in building a bigger component
    2. Functional component access directly via props argument passed. In a class-based component, props are accessible via this.props.
    3. A class-based component is a more complex structure. It is an instance of a class derived from React. Component class. The class must implement a render() member function which returns a React component to be rendered
    4. The class-based component can also use lifecycle methods but functional component can’t use lifecycle methods.
    5. Functional components are a very light weighted component in comparison to class-based react component
  • What are the ways to write react components?

    here are two ways of writing a react component

    • Functional component
      • It uses a simple function which returns the JSX
    • Class-based component
      • It used the class keyword introduced in ES6. it implements render lifecycle method which returns the JSX.

    Example of functional component

    Functional component

    Example of class-based component

    Class-based component
    /* Class based component */
    import React, { Component } from 'react';
    import { Text } from 'react-native';
    
    export default class Greeting extends Component {
        render() {
            return (
                <Text>Hello {this.props.name} !</Text>
            );
        }
    }
    
    /* Functional component */
    import React, { Component } from 'react';
    import { Text } from 'react-native';
    
    export default function Greeting(props) {
            return (
                <Text>Hello {props.name} !</Text>
            );
    }

    cases are known as a presentational or dumb component. The functional component gets information via props from its parent component and renders the information. You can see that the functional component accepts props as an argument. ES6 arrow function also is used to define a functional component. The functional component doesn’t store any state and also doesn’t override any lifecycle method of React component. The class-based component has the ability to store state within the component and based on its state value behave differently. The latest version of React 16.8 has included a new feature called React hooks by which we can add state in a functional component.