Thursday, August 22, 2019

React Interview Questions

Q: Functional vs Class-Components in React?

The simplest way to define a component in React is to write a JavaScript function:
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
......................................................................................................................................................................................................................
But we can also use the ES6 class syntax to write components.
class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
Both versions are equivalent and will give us the exact same output.

When should I use a function and when a class?
Syntax

A functional component is just a plain JavaScript function which accepts props as an argument and returns a React element.
1. we cannot use setState() in our component.
2. Another feature which we cannot use in functional components are lifecycle hooks.

So why should I use functional components at all?

1. Functional component are much easier to read and test because they are plain JavaScript functions without state or lifecycle-hooks
2. You end up with less code
3.They help you to use best practices. 
4. It will get easier to separate container and presentational components because we need to think more about our component’s state if we don’t have access to setState() in our component
The React team mentioned that there may be a performance boost for functional component in future React versions

No this Keyword
No Class Needed

Enforced Best Practices
Stateless functional components are useful for dumb/presentational components.
 Presentational components focus on the UI rather than behavior,
so it’s important to avoid using state in presentational components.
Instead, state should be managed by higher-level “container” components, or via Flux/Redux/etc. Stateless functional components don’t support state or lifecycle methods.
This is a good thing. Why? Because it protects from laziness.
Since stateless functional components don’t support local state,












A class component requires us to extend from React.Component and create a render function which returns a React element.



.....................................................................................................................................................................................................................................
Hooks

What are Hooks?
>> A Hook is a Special function.
>> Introduced in React 16.8.
>> Use State and other React features without writing a class
>> Hooks don't work inside classes.

Why use React Hooks
>> Avoid the confusion of this keyword and bind this.
>> Complex components become hard to understand.
>> Hooks make it easy for you to test


>>  unlike this.state
>>  you can use state Hooks more than once in a single component
like
only once
this.state ={
name:"",
city:""
}

const [name, setName]=useState()
const [City, setCity]=useState()

Rules of Hooks
>> Call at the top level, Don't call Hooks inside loops, conditions, or nested functions
>> Call from React function components ,
Don't call Hooks from regular JavaScripts functions

plugin are available follow or not hooks
eslint-plugin-react-hooks

types of Hooks mainly two importants
State Hooks: useState
Effect Hooks: useEffect

const [count, setCount]= useState(0)
call this function useState()
pass the initial State inside it
like
useState(initialState)
return an array is to be two  items
1. First is state variable which will be create
2. and second one function that can be used to set the state


.............................................................................................................................................................................................................................................

#useEffect

Operations like data fetching, subscriptions, or manually

changing the DOM from React Component are "Side Effect" or "effect"

>> It serves the same purpose as  componentDidMount, componentDidUpdate, componentWillUnmount
>> Can use multiple useEffect() in component

When is useEffect() called?
>> Initail render
>> State changes
>> Component unmounts

clean up
>> Effect that donot require cleanup
>> It's important to cleanup to avoid memory leak
>> If our effect returns a function, React runs it on unmounts
and re-render for clean up.


skipping Effect for performance optimization

>> Skip applying an effect if certain values haven't
changed between re-render
>> Pass an array as an optional second argument to useEffect

>> pass an Empty array([]), If you want to run an effect
and clean it up only once(on mount and unmount)

example as below!

Example : #1
src/component/MyChild 

import React, { useEffect } from 'react'
const MyChild = () => {
    useEffect(() => {
        console.log('initial render: mounted')
        return () => {
            console.log('clean up!:unmounted')
        }
    })

    return (
        <>
            <h1>hello</h1>
        </>
    )
}
export default MyChild

.............................................................................................................................................................................................................
import React, { Component, useState } from 'react'
import MyChild from '../src/components/Child'

const Home =()=>{
  const [showItem, setShowItem]=useState(false)

  console.log(showItem)

  return(
    <>
    <button onClick={()=>setShowItem(!showItem)}>toggle</button>
    {showItem? <MyChild/>:''}
    </>
  )
}

export default class App extends Component {
  render() {
    return (
      <>
      <Home/>
      </>
    )
  }
}


.........................................................................................................................................................................................................
A guide to useState in React

useState is a hook that allows you to have state variables in functional components.

There are two types of components in React,

  • class components.
  • functional components
Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods:

class Message extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      message: ‘’ 
    };
  }
  componentDidMount() {
    /* ... */
  }
  render() {
    return <div>{this.state.message}</div>;
  }
}

Functional components are functions that just accept arguments as the properties of the component and return valid JSX:

function Message(props) {
  return <div>{props.message}</div>
}
// Or as an arrow function
const Message = (props) =>  <div>{props.message}</div>
As you can see, there are no state or lifecycle methods.


















Rules of Hooks

. Only call Hooks at the top level
. Do not call Hooks inside loops, conditions or nested functions

import React, {useState} from 'react'
const App = () => {
  if(true){
    useState()
  }
  return (
    <div>
      <h4>Hey</h4>
    </div>
  )
}
export default App

..............................................................................................................................................................................................................................
Hooks Programming  
with previous state (ie c=>c+1)

import React, { useState } from 'react'
const App =()=>{
  const [count, setCount] =useState(0)
  return(
    <>
    <button onClick={()=>setCount(c=>c+1)}>Click{count}</button>
    </>
  )
}
export default App
..............................................................................................................................................................................................................................
import React, { useState } from 'react'
const App = () => {
  const [{ count1, count2 }, setCount] = useState({ count1: 10, count2: 20 })
  return (
    <>
    <button onClick={() => setCount(currentState => ({ count1: currentState.count1 + 1, count2: currentState.count2 + 1 }))}>Click{count1}-{count2}</button>
    </>
  )
}
export default App
...........................................................................................................................................................................................................................
import React, { useState } from 'react'
const App = () => {
  const [count1, setCount1] = useState(20)
  const [count2, setCount2] = useState(20)
  return (
    <>
      <button onClick={() => {
        setCount1(currentState => currentState + 1)
        setCount2(currentState => currentState + 1)
      }}>Click{count1}-{count2}</button>
    </>
  )
}

export default App
..........................................................................................................................................................................................................................
Simple Form

import React, { useState } from 'react'
const App = () => {
  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")

  const onSubmit = (event) => {
    event.preventDefault()
    console.log(email, password)
  }

  return (
    <>
      <form onSubmit={onSubmit}>
        <input
          type="text"
          name="email"
          value={email}
          onChange={(email) => setEmail(email.target.value)}
        />
        <br></br>
        <input
          type="password"
          name="password"
          value={password}
          onChange={(password) => setPassword(password.target.value)}
        /><br></br>
        <button type='submit'>Submit</button>
      </form>
    </>
  )
}
export default App
................................................................................................................................................................................................................................

import React, { useState } from 'react'

const App = () => {
  const [values, handleChanges] = useState({ email: '', password: '' })

  const onSubmit = (event) => {
    event.preventDefault()
    console.log(values)
  }
  const handleChange=(e)=>{
    handleChanges({...values, [e.target.value]:e.target.name})
  }

  return (
    <>
      <form onSubmit={onSubmit} autoComplete="off">
        <input
          autoComplete={true}
          placeholder='Enter email'
          type="text"
          name="email"
          value={values.email}
          onChange={handleChange}
        />
        <br></br>
        <input
          autoComplete={true}
          type="text"
          name="password"
          placeholder="password"
          value={values.password}
          onChange={handleChange}
        /><br></br>
        <button type='submit'>Submit</button>
      </form>
    </>
  )
}

export default App
........................................................................................................................................................................................................................






.................................................................................................................................................................................................................................







.................................................................................................................................................................................................................................








.................................................................................................................................................................................................................................
React Native






In React Native, there is no DOM here we use Native Components which are provided by platforms such as iOS and Android.

In React Native there are no web views here, such as ionic uses web view for the application.

Basic or Core components – View, Text, Image, ScrollView, TextInput , StyleSheet etc.

List components – FlatList and SectionList.

User Interface or Form Control components: Picker, slider, button, switch.

iOS Specific Components: ActionSheetIOS, SegmentedControlIOS, AlertIOS, PushNotificationsIOS.

Android Specific components: DatePickerAndroid, TimePickerAndroid, ViewPagerAndroid, ToastAndroid, PermissionsAndroid.

Other important components: Alert, Animated, CameraRoll, Dimensions, Clipboard, StatusBar, Linking, Keyboard, ActivityIndicator, WebView, and Modal, etc.

















.................................................................................................................................................................................................................................


.................................................................................................................................................................................................................................
Why can't browsers read JSX?

React uses JSX(JavaScript extensions) that allows us to write JavaScript that looks like HTML.
But given JSX is not valid JavaScript. web browser cann't read it directly.
So, if JavaScript files contain JSX. that file will have to be transpired.
you  need a transpiler to convert your JSX
to regular JavaScript that browsers can underStand.
The most widely used transpiler right now is Babel.

.................................................................................................................................................................................................................................
What do you understand from "In React, everything is a component"

Components are the building blocks of a React application's UI.
These components split up the entire UI into small independent and reusable pieces.
Then it renders each of these components independent of each other without affecting the rest of the UI.


.................................................................................................................................................................................................................................
List Some of the React's significatns benefits.

It increases the applications's performance, Utilizing a virtual DOM diff techniques
React JS know when and what specific parts of the DOM tree exactly
to re-render or when and specific parts of DOM to ignore because
virtual DOM detects when and which the data has changed.
This makes the React app react fast.
A UI that reacts promptly is crucial in enhancing the user experience


.................................................................................................................................................................................................................................
What is use of platform module in React Native?

React Native Platform module is used to detect the platform of device in which the application is running. You can use the below code detect platform in React Native.

import {Platform, StyleSheet} from 'react-native';
const styles = StyleSheet.create({
  height: Platform.OS === 'ios' ? 200 : 100,
});

.................................................................................................................................................................................................................................







What are Flutter & React Native?
Flutter and React Native are both cross-platform mobile development frameworks. React Native was developed by Facebook and was initially released in May 2015. It was later discovered by a larger community, and ever since it has become mainly community-driven. Flutter, on the other hand, is considered as a newer framework; its first stable version was released in December 2018. Apps using React Native are written in JavaScript, while apps using Flutters are written in Dart.




No comments:

Post a Comment