React 2of4 Flashcards

#101-200

1
Q

What is the difference between setState() and replaceState() methods?

A

When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How to listen to state changes?

A

The componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed.

componentDidUpdate(object prevProps, object prevState)
Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState) for state changes. It has been deprecated in latest releases.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the recommended approach of removing an array element in React state?

A

The better approach is to use Array.prototype.filter() method.

For example, let’s create a removeItem() method for updating the state.

removeItem(index) {
this.setState({
data: this.state.data.filter((item, i) => i !== index)
})
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Is it possible to use React without rendering HTML?

A

It is possible with latest version (>=16.2). Below are the possible options:

render() {
return false
}
render() {
return null
}
render() {
return []
}
render() {
return
}
render() {
return <>>
}
Returning undefined won’t work.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How to pretty print JSON with React?

A

We can use

tag so that the formatting of the JSON.stringify() is retained: 

const data = { name: 'John', age: 42 } 

class User extends React.Component {
render() {
return (
~~~

{JSON.stringify(data, null, 2)}

)
}
}

React.render(, document.getElementById(‘container’))
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Why you can’t update props in React?

A

The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can’t modify received props.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How to focus an input element on page load?

A

You can do it by creating ref for input element and using it in componentDidMount():

class App extends React.Component{ 
 componentDidMount() { 
 this.nameInput.focus() 
 } 

render() {
return (

this.nameInput = input}
defaultValue={‘Will focus’}
/>

)
}
}

ReactDOM.render(, document.getElementById(‘app’))
Also in Functional component (react 16.08 and above)

import React, {useEffect, useRef} from ‘react’;

const App = () =\> { 
 const inputElRef = useRef(null) 

useEffect(()=>{
inputElRef.current.focus()
}, [])

return(

)
}

ReactDOM.render(, document.getElementById(‘app’))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What are the possible ways of updating objects in state?

A

[i] Calling setState() with an object to merge with state:

Using Object.assign() to create a copy of the object:

const user = Object.assign({}, this.state.user, { age: 42 }) 
this.setState({ user }) 
Using spread operator: 
const user = { ...this.state.user, age: 42 } 
this.setState({ user }) 

[ii] Calling setState() with a function:

this.setState(prevState => ({
user: {
…prevState.user,
age: 42
}
}))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

(question #109 not given - https://github.com/sudheerj/reactjs-interview-questions#what-is-react )

A

(question and answer #109 not given)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How can we find the version of React at runtime in the browser?

A

You can use React.version to get the version.

const REACT_VERSION = React.version

ReactDOM.render(

{React version: ${REACT_VERSION}}
,
document.getElementById(‘app’)
)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What are the approaches to include polyfills in your create-react-app?

A

There are approaches to include polyfills in create-react-app,

[i] Manual import from core-js:

Create a file called (something like) polyfills.js and import it into root index.js file. Run npm install core-js or yarn add core-js and import your specific required features.

import ‘core-js/fn/array/find’
import ‘core-js/fn/array/includes’
import ‘core-js/fn/number/is-nan’
Using Polyfill service:

[ii] Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html:

In the above script we had to explicitly request the Array.prototype.includes feature as it is not included in the default feature set.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

How to use https instead of http in create-react-app?

A

You just need to use HTTPS=true configuration. You can edit your package.json scripts section:

“scripts”: {
“start”: “set HTTPS=true && react-scripts start”
}
or just run set HTTPS=true && npm start

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

How to avoid using relative path imports in create-react-app?

A

Create a file called .env in the project root and write the import path:

NODE_PATH=src/app
After that restart the development server. Now you should be able to import anything inside src/app without relative paths.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

How to add Google Analytics for React Router?

A

Add a listener on the history object to record each page view:

history.listen(function (location) {
window.ga(‘set’, ‘page’, location.pathname + location.search)
window.ga(‘send’, ‘pageview’, location.pathname + location.search)
})

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to update a component every second?

A

You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.

componentDidMount() {
this.interval = setInterval(() => this.setState({ time: Date.now() }), 1000)
}

componentWillUnmount() {
clearInterval(this.interval)
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

How do you apply vendor prefixes to inline styles in React?

A

React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

How to import and export components using React and ES6?

A

You should use default for exporting the components

import React from ‘react’
import User from ‘user’

export default class MyProfile extends React.Component { 
 render(){ 
 return ( 

//…

 ) 
 } 
} 
With the export specifier, the MyProfile is going to be the member and exported to this module and the same can be imported without mentioning the name in other components.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Why is a component constructor called only once?

A

React’s reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it’s the same component as before, so reuses the previous instance rather than creating a new one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to define constants in React?

A

You can use ES7 static field to define constant.

class MyComponent extends React.Component { 
 static DEFAULT\_PAGINATION = 10 
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

How to programmatically trigger click event in React?

A

You could use the ref prop to acquire a reference to the underlying HTMLInputElement object through a callback, store the reference as a class property, then use that reference to later trigger a click from your event handlers using the HTMLElement.click method.

This can be done in two steps:

[i] Create ref in render method:

this.inputElement = input} />
[ii] Apply click event in your event handler:

this.inputElement.click()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Is it possible to use async/await in plain React?

A

If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin. React Native ships with Babel and a set of transforms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What are the common folder structures for React?

A

There are two common practices for React project file structure.

Grouping by features or routes:

One common way to structure projects is locate CSS, JS, and tests together, grouped by feature or route.

common/
├─ Avatar.js
├─ Avatar.css
├─ APIUtils.js
└─ APIUtils.test.js
feed/
├─ index.js
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
└─ FeedAPI.js
profile/
├─ index.js
├─ Profile.js
├─ ProfileHeader.js
├─ ProfileHeader.css
└─ ProfileAPI.js
Grouping by file type:

Another popular way to structure projects is to group similar files together.

api/
├─ APIUtils.js
├─ APIUtils.test.js
├─ ProfileAPI.js
└─ UserAPI.js
components/
├─ Avatar.js
├─ Avatar.css
├─ Feed.js
├─ Feed.css
├─ FeedStory.js
├─ FeedStory.test.js
├─ Profile.js
├─ ProfileHeader.js
└─ ProfileHeader.css

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

What are the popular packages for animation?

A

React Transition Group and React Motion are popular animation packages in React ecosystem.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the benefit of styles modules?

A

It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules.

For example, these styles could be extracted into a separate component:

export const colors = {
white,
black,
blue
}

export const space = [
0,
8,
16,
32,
64
]
And then imported individually in other components:

import { space, colors } from ‘./styles’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
Q

What are the popular React-specific linters?

A

ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types.

Another popular plugin is eslint-plugin-jsx-a11y, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt text and tabindex, for example, will not be picked up by regular plugins.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
26
Q

How to make AJAX call and in which component lifecycle methods should I make an AJAX call?

A

You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved.

For example, the employees list fetched from API and set local state:

class MyComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
employees: [],
error: null
}
}

componentDidMount() {
fetch(‘https://api.example.com/items’)
.then(res => res.json())
.then(
(result) => {
this.setState({
employees: result.employees
})
},
(error) => {
this.setState({ error })
}
)
}

render() {
const { error, employees } = this.state
if (error) {
return

Error: {error.message}
;
} else {
return (

{employees.map(employee => ( * {employee.name}-{employee.experience}

))}
)
}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
27
Q

What are render props?

A

Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element.

(

{Hello ${data.target}}

)}/>
Libraries such as React Router and DownShift are using this pattern

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
28
Q

-

A

-

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
29
Q

What is React Router?

A

React Router is a powerful routing library built on top of React that helps you add new screens and flows to your application incredibly quickly, all while keeping the URL in sync with what’s being displayed on the page.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
30
Q

How React Router is different from history library?

A

React Router is a wrapper around the history library which handles interaction with the browser’s window.history with its browser and hash histories. It also provides memory history which is useful for environments that don’t have global history, such as mobile app development (React Native) and unit testing with Node.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
31
Q

What are the components of React Router v4?

A

React Router v4 provides below 3 components:

[i]
[ii]
[iii]
The above components will create browser, hash, and memory history instances. React Router v4 makes the properties and methods of the history instance associated with your router available through the context in the router object.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

What is the purpose of push() and replace() methods of history?

A

A history instance has two methods for navigation purpose.

[i] push()
[ii] replace()

If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How do you programmatically navigate using React Router v4?

A

There are three different ways to achieve programmatic routing/navigation within components.

[i] Using the withRouter() higher-order function:

The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context.

import { withRouter } from ‘react-router-dom’ // this also works with ‘react-router-native’

const Button = withRouter(({ history }) =\> ( 
 { history.push('/new-location') }} 
 \> 
 {'Click Me!'} 

))

[ii] Using component and render props pattern:

The component passes the same props as withRouter(), so you will be able to access the history methods through the history prop.

import { Route } from ‘react-router-dom’

const Button = () => (
(
{ history.push(‘/new-location’) }}
>
{‘Click Me!’}

)} />
)

[iii] Using context:

This option is not recommended and treated as unstable API.

const Button = (props, context) => (
{
context.history.push(‘/new-location’)
}}
>
{‘Click Me!’}

)

Button.contextTypes = {
history: React.PropTypes.shape({
push: React.PropTypes.func.isRequired
})
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
34
Q

How to get query parameters in React Router v4?

A

The ability to parse query strings was taken out of React Router v4 because there have been user requests over the years to support different implementation. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library.

const queryString = require('query-string'); 
const parsed = queryString.parse(props.location.search); 
You can also use URLSearchParams if you want something native: 
const params = new URLSearchParams(props.location.search) 
const foo = params.get('name') 
You should use a polyfill for IE11.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
35
Q

Why you get “Router may have only one child element” warning?

A

You have to wrap your Route’s in a block because is unique in that it renders a route exclusively.

At first you need to add Switch to your imports:

import { Switch, Router, Route } from ‘react-router’
Then define the routes within block:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
36
Q

How to pass params to history.push method in React Router v4?

A

While navigating you can pass props to the history object:

this.props.history.push({
pathname: ‘/template’,
search: ‘?name=sudheer’,
state: { detail: response.data }
})
The search property is used to pass query params in push() method.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

How to implement default or NotFound page?

A

A renders the first child that matches. A with no path always matches. So you just need to simply drop path attribute as below

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

How to get history on React Router v4?

A

Below are the list of steps to get history object on React Router v4,

[i] Create a module that exports a history object and import this module across the project.

For example, create history.js file:

import { createBrowserHistory } from ‘history’

export default createBrowserHistory({
/* pass a configuration object here if needed */
})

[ii] You should use the component instead of built-in routers. Import the above history.js inside index.js file:

import { Router } from ‘react-router-dom’
import history from ‘./history’
import App from ‘./App’

ReactDOM.render((

), holder)

[iii] You can also use push method of history object similar to built-in history object:

// some-other-file.js 
import history from './history' 

history.push(‘/go-here’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
39
Q

How to perform automatic redirect after login?

A

The react-router package provides component in React Router. Rendering a will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.

import React, { Component } from ‘react’
import { Redirect } from ‘react-router’

export default class LoginComponent extends Component { 
 render() { 
 if (this.state.isLoggedIn === true) { 
 return 
 } else { 
 return

{‘Login Please’}

}
}
}

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

What is React Intl (Internalization)?

A

The React Intl (internalization) library makes internalization in React straightforward, with off-the-shelf components and an API that can handle everything from formatting strings, dates, and numbers, to pluralization. React Intl is part of FormatJS which provides bindings to React via its components and API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

What are the main features of React Intl?

A

Below are the main features of React Intl,

Display numbers with separators.
Display dates and times correctly.
Display dates relative to “now”.
Pluralize labels in strings.
Support for 150+ languages.
Runs in the browser and Node.
Built on standards.

42
Q

What are the two ways of formatting in React Intl?

A

The library provides two ways to format strings, numbers, and dates:

Using react components:

Using an API:

const messages = defineMessages({ 
 accountMessage: { 
 id: 'account', 
 defaultMessage: 'The amount is less than minimum balance.', 
 } 
}) 

formatMessage(messages.accountMessage)

43
Q

How to use as placeholder using React Intl?

A

The components from react-intl return elements, not plain text, so they can’t be used for placeholders, alt text, etc. In that case, you should use lower level API formatMessage(). You can inject the intl object into your component using injectIntl() higher-order component and then format the message using formatMessage() available on that object.

import React from ‘react’
import { injectIntl, intlShape } from ‘react-intl’

const MyComponent = ({ intl }) =\> { 
 const placeholder = intl.formatMessage({id: 'messageId'}) 
 return 
} 

MyComponent.propTypes = {
intl: intlShape.isRequired
}

export default injectIntl(MyComponent)

44
Q

How to access current locale with React Intl?

A

You can get the current locale in any component of your application using injectIntl():

import { injectIntl, intlShape } from ‘react-intl’

const MyComponent = ({ intl }) => (

{The current locale is ${intl.locale}}

)

MyComponent.propTypes = {
intl: intlShape.isRequired
}

export default injectIntl(MyComponent)

45
Q

How to format date using React Intl?

A

The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component. The method is used internally by instances of FormattedDate and it returns the string representation of the formatted date.

import { injectIntl, intlShape } from ‘react-intl’

const stringDate = this.props.intl.formatDate(date, { 
 year: 'numeric', 
 month: 'numeric', 
 day: 'numeric' 
}) 

const MyComponent = ({intl}) => (

{The formatted date is ${stringDate}}

)

MyComponent.propTypes = {
intl: intlShape.isRequired
}

export default injectIntl(MyComponent)

46
Q

What is Shallow Renderer in React testing?

A

Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered.

For example, if you have the following component:

function MyComponent() { 
 return (

{‘Title’}
{‘Description’}

)
}
Then you can assert as follows:

import ShallowRenderer from ‘react-test-renderer/shallow’

// in your test 
const renderer = new ShallowRenderer() 
renderer.render() 

const result = renderer.getRenderOutput()

expect(result.type).toBe(‘div’)
expect(result.props.children).toEqual([
{‘Title’},
{‘Description’}
])

47
Q

What is TestRenderer package in React?

A

This package provides a renderer that can be used to render components to pure JavaScript objects, without depending on the DOM or a native mobile environment. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.

import TestRenderer from ‘react-test-renderer’

const Link = ({page, children}) => {children}

const testRenderer = TestRenderer.create( 
 {'Facebook'} 
) 
console.log(testRenderer.toJSON()) 
// { 
// type: 'a', 
// props: { href: 'https://www.facebook.com/' }, 
// children: ['Facebook'] 
// }
48
Q

What is the purpose of ReactTestUtils package?

A

ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing.

49
Q

What is Jest?

A

Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment. It’s often used for testing components.

50
Q

What are the advantages of Jest over Jasmine?

A

There are couple of advantages compared to Jasmine:

Automatically finds tests to execute in your source code.
Automatically mocks dependencies when running your tests.
Allows you to test asynchronous code synchronously.
Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line.
Runs tests in parallel processes so that they finish sooner.

51
Q

Give a simple example of Jest test case

A

Let’s write a test for a function that adds two numbers in sum.js file:

const sum = (a, b) => a + b

export default sum
Create a file named sum.test.js which contains actual test:

import sum from ‘./sum’

test(‘adds 1 + 2 to equal 3’, () => {
expect(sum(1, 2)).toBe(3)
})
And then add the following section to your package.json:

{
“scripts”: {
“test”: “jest”
}
}
Finally, run yarn test or npm test and Jest will print a result:

$ yarn test
PASS ./sum.test.js
✓ adds 1 + 2 to equal 3 (2ms)

52
Q

What is flux?

A

Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this pattern internally when working with React.

The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:

53
Q

What is Redux?

A

Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with React, or with any other view library. It is tiny (about 2kB) and has no dependencies.

54
Q

What are the core principles of Redux?

A

Redux follows three fundamental principles:

[i] Single source of truth: The state of your whole application is stored in an object tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application.

[ii] State is read-only: The only way to change the state is to emit an action, an object describing what happened. This ensures that neither the views nor the network callbacks will ever write directly to the state.

[iii] Changes are made with pure functions: To specify how the state tree is transformed by actions, you write reducers. Reducers are just pure functions that take the previous state and an action as parameters, and return the next state.

55
Q

What are the downsides of Redux compared to Flux?

A

Instead of saying downsides we can say that there are few compromises of using Redux over Flux. Those are as follows:

[i] You will need to learn to avoid mutations: Flux is un-opinionated about mutating data, but Redux doesn’t like mutations and many packages complementary to Redux assume you never mutate the state. You can enforce this with dev-only packages like redux-immutable-state-invariant, Immutable.js, or instructing your team to write non-mutating code.

[ii] You’re going to have to carefully pick your packages: While Flux explicitly doesn’t try to solve problems such as undo/redo, persistence, or forms, Redux has extension points such as middleware and store enhancers, and it has spawned a rich ecosystem.

[iii] There is no nice Flow integration yet: Flux currently lets you do very impressive static type checks which Redux doesn’t support yet.

56
Q

What is the difference between mapStateToProps() and mapDispatchToProps()?

A

mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components):

const mapStateToProps = (state) =\> { 
 return { 
 todos: getVisibleTodos(state.todos, state.visibilityFilter) 
 } 
} 
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state): 
const mapDispatchToProps = (dispatch) =\> { 
 return { 
 onTodoClick: (id) =\> { 
 dispatch(toggleTodo(id)) 
 } 
 } 
} 
It is recommended to always use the “object shorthand” form for the mapDispatchToProps. 

Redux wraps it in another function that looks like (…args) => dispatch(onTodoClick(…args)), and pass that wrapper function as a prop to your component.

 const mapDispatchToProps = ({ 
 onTodoClick 
 })
57
Q

Can I dispatch an action in reducer?

A

Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.

58
Q

How to access Redux store outside a component?

A

You just need to export the store from the module where it created with createStore(). Also, it shouldn’t pollute the global window object.

store = createStore(myReducer)

export default store

59
Q

What are the drawbacks of MVW pattern?

A

[i] DOM manipulation is very expensive which causes applications to behave slow and inefficient.

[ii] Due to circular dependencies, a complicated model was created around models and views.

[iii] Lot of data changes happens for collaborative applications(like Google Docs).

[iv] No way to do undo (travel back in time) easily without adding so much extra code.

60
Q

Are there any similarities between Redux and RxJS?

A

These libraries are very different for very different purposes, but there are some vague similarities.

Redux is a tool for managing state throughout the application. It is usually used as an architecture for UIs. Think of it as an alternative to (half of) Angular. RxJS is a reactive programming library. It is usually used as a tool to accomplish asynchronous tasks in JavaScript. Think of it as an alternative to Promises. Redux uses the Reactive paradigm because the Store is reactive. The Store observes actions from a distance, and changes itself. RxJS also uses the Reactive paradigm, but instead of being an architecture, it gives you basic building blocks, Observables, to accomplish this pattern.

61
Q

How to dispatch an action on load?

A

You can dispatch an action in componentDidMount() method and in render() method you can verify the data.

class App extends Component { 
 componentDidMount() { 
 this.props.fetchData() 
 } 

render() {
return this.props.isLoaded
?

{‘Loaded’}{‘Not Loaded’}

}
}

const mapStateToProps = (state) =\> ({ 
 isLoaded: state.isLoaded 
}) 

const mapDispatchToProps = { fetchData }

export default connect(mapStateToProps, mapDispatchToProps)(App)

62
Q

How to use connect() from React Redux?

A

You need to follow two steps to use your store in your container:

[i] Use mapStateToProps(): It maps the state variables from your store to the props that you specify.

[ii] Connect the above props to your container: The object returned by the mapStateToProps function is connected to the container. You can import connect() from react-redux.

import React from ‘react’
import { connect } from ‘react-redux’

class App extends React.Component { 
 render() { 
 return

{this.props.containerData}

}
}

function mapStateToProps(state) { 
 return { containerData: state.data } 
} 

export default connect(mapStateToProps)(App)

63
Q

How to reset state in Redux?

A

You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers().

For example, let us take rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action.

const appReducer = combineReducers({ 
 /\* your app's top-level reducers \*/ 
}) 
const rootReducer = (state, action) =\> { 
 if (action.type === 'USER\_LOGOUT') { 
 state = undefined 
 } 
 return appReducer(state, action) 
} 
In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key. 
const appReducer = combineReducers({ 
 /\* your app's top-level reducers \*/ 
}) 
const rootReducer = (state, action) =\> { 
 if (action.type === 'USER\_LOGOUT') { 
 Object.keys(state).forEach(key =\> { 
 storage.removeItem(`persist:${key}`) 
 }) 

state = undefined
}

 return appReducer(state, action) 
}
64
Q

Whats the purpose of at symbol in the Redux connect decorator?

A

The @ symbol is in fact a JavaScript expression used to signify decorators. Decorators make it possible to annotate and modify classes and properties at design time.

Let’s take an example setting up Redux without and with a decorator.

Without decorator:

import React from ‘react’
import * as actionCreators from ‘./actionCreators’
import { bindActionCreators } from ‘redux’
import { connect } from ‘react-redux’

function mapStateToProps(state) { 
 return { todos: state.todos } 
} 
function mapDispatchToProps(dispatch) { 
 return { actions: bindActionCreators(actionCreators, dispatch) } 
} 
class MyApp extends React.Component { 
 // ...define your main app here 
} 

export default connect(mapStateToProps, mapDispatchToProps)(MyApp)
With decorator:

import React from ‘react’
import * as actionCreators from ‘./actionCreators’
import { bindActionCreators } from ‘redux’
import { connect } from ‘react-redux’

function mapStateToProps(state) { 
 return { todos: state.todos } 
} 
function mapDispatchToProps(dispatch) { 
 return { actions: bindActionCreators(actionCreators, dispatch) } 
} 
@connect(mapStateToProps, mapDispatchToProps) 
export default class MyApp extends React.Component { 
 // ...define your main app here 
} 
The above examples are almost similar except the usage of decorator. The decorator syntax isn't built into any JavaScript runtimes yet, and is still experimental and subject to change. You can use babel for the decorators support.
65
Q

What is the difference between React context and React Redux?

A

You can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for.

Whereas Redux is much more powerful and provides a large number of features that the Context API doesn’t provide. Also, React Redux uses context internally but it doesn’t expose this fact in the public API.

66
Q

Why are Redux state functions called reducers?

A

Reducers always return the accumulation of the state (based on all previous and current actions). Therefore, they act as a reducer of state. Each time a Redux reducer is called, the state and action are passed as parameters. This state is then reduced (or accumulated) based on the action, and then the next state is returned. You could reduce a collection of actions and an initial state (of the store) on which to perform these actions to get the resulting final state.

67
Q

How to make AJAX request in Redux?

A

You can use redux-thunk middleware which allows you to define async actions.

Let’s take an example of fetching specific account as an AJAX call using fetch API:

export function fetchAccount(id) {
return dispatch => {
dispatch(setLoadingAccountState()) // Show a loading spinner
fetch(/account/${id}, (response) => {
dispatch(doneFetchingAccount()) // Hide loading spinner
if (response.status === 200) {
dispatch(setAccount(response.json)) // Use a normal function to set the received state
} else {
dispatch(someError)
}
})
}
}

function setAccount(data) { 
 return { type: 'SET\_Account', data: data } 
}
68
Q

Should I keep all component’s state in Redux store?

A

Keep your data in the Redux store, and the UI related state internally in the component.

69
Q

What is the proper way to access Redux store?

A

The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component’s functionality in React. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates.

Let’s take an example of component using connect:

import { connect } from ‘react-redux’
import { setVisibilityFilter } from ‘../actions’
import Link from ‘../components/Link’

const mapStateToProps = (state, ownProps) =\> ({ 
 active: ownProps.filter === state.visibilityFilter 
}) 
const mapDispatchToProps = (dispatch, ownProps) =\> ({ 
 onClick: () =\> dispatch(setVisibilityFilter(ownProps.filter)) 
}) 
const FilterLink = connect( 
 mapStateToProps, 
 mapDispatchToProps 
)(Link) 

export default FilterLink
Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux developers almost always recommend using connect() over accessing the store directly (using context API).

class MyComponent { 
 someMethod() { 
 doSomethingWith(this.context.store) 
 } 
}
70
Q

What is the difference between component and container in React Redux?

A

Component is a class or function component that describes the presentational part of your application.

Container is an informal term for a component that is connected to a Redux store. Containers subscribe to Redux state updates and dispatch actions, and they usually don’t render DOM elements; they delegate rendering to presentational child components.

71
Q

What is the purpose of the constants in Redux?

A

Constants allows you to easily find all usages of that specific functionality across the project when you use an IDE. It also prevents you from introducing silly bugs caused by typos – in which case, you will get a ReferenceError immediately.

Normally we will save them in a single file (constants.js or actionTypes.js).

export const ADD_TODO = ‘ADD_TODO’
export const DELETE_TODO = ‘DELETE_TODO’
export const EDIT_TODO = ‘EDIT_TODO’
export const COMPLETE_TODO = ‘COMPLETE_TODO’
export const COMPLETE_ALL = ‘COMPLETE_ALL’
export const CLEAR_COMPLETED = ‘CLEAR_COMPLETED’

In Redux, you use them in two places:

[i] During action creation:

Let’s take actions.js:

import { ADD_TODO } from ‘./actionTypes’;

export function addTodo(text) {
return { type: ADD_TODO, text }
}

[ii] In reducers:

Let’s create reducer.js:

import { ADD_TODO } from ‘./actionTypes’

export default (state = [], action) =\> { 
 switch (action.type) { 
 case ADD\_TODO: 
 return [ 
 ...state, 
 { 
 text: action.text, 
 completed: false 
 } 
 ]; 
 default: 
 return state 
 } 
}
72
Q

What are the different ways to write mapDispatchToProps()?

A

There are a few ways of binding action creators to dispatch() in mapDispatchToProps().

Below are the possible options:

const mapDispatchToProps = (dispatch) =\> ({ 
 action: () =\> dispatch(action()) 
}) 
const mapDispatchToProps = (dispatch) =\> ({ 
 action: bindActionCreators(action, dispatch) 
}) 
const mapDispatchToProps = { action } 
The third option is just a shorthand for the first one.
73
Q

What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?

A

If the ownProps parameter is specified, React Redux will pass the props that were passed to the component into your connect functions. So, if you use a connected component:

import ConnectedComponent from ‘./containers/ConnectedComponent’;

The ownProps inside your mapStateToProps() and mapDispatchToProps() functions will be an object:

{ user: ‘john’ }
You can use this object to decide what to return from those functions.

74
Q

How to structure Redux top level directories?

A

Most of the applications has several top-level directories as below:

[1] Components: Used for dumb components unaware of Redux.
[2] Containers: Used for smart components connected to Redux.
[3] Actions: Used for all action creators, where file names correspond to part of the app.
[4] Reducers: Used for all reducers, where files name correspond to state key.
[5] Store: Used for store initialization.
This structure works well for small and medium size apps.

75
Q

What is redux-saga?

A

redux-saga is a library that aims to make side effects (asynchronous things like data fetching and impure things like accessing the browser cache) in React/Redux applications easier and better.

It is available in NPM:

$ npm install –save redux-saga

76
Q

What is the mental model of redux-saga?

A

Saga is like a separate thread in your application, that’s solely responsible for side effects. redux-saga is a redux middleware, which means this thread can be started, paused and cancelled from the main application with normal Redux actions, it has access to the full Redux application state and it can dispatch Redux actions as well.

77
Q

What are the differences between call() and put() in redux-saga?

A

Both call() and put() are effect creator functions. call() function is used to create effect description, which instructs middleware to call the promise. put() function creates an effect, which instructs middleware to dispatch an action to the store.

Let’s take example of how these effects work for fetching particular user data.

function\* fetchUserSaga(action) { 
 // `call` function accepts rest arguments, which will be passed to `api.fetchUser` function. 
 // Instructing middleware to call promise, it resolved value will be assigned to `userData` variable 
 const userData = yield call(api.fetchUser, action.userId) 
 // Instructing middleware to dispatch corresponding action. 
 yield put({ 
 type: 'FETCH\_USER\_SUCCESS', 
 userData 
 }) 
}
78
Q

What is Redux Thunk?

A

Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch() and getState() as parameters.

79
Q

What are the differences between redux-saga and redux-thunk?

A

Both Redux Thunk and Redux Saga take care of dealing with side effects. In most of the scenarios, Thunk uses Promises to deal with them, whereas Saga uses Generators. Thunk is simple to use and Promises are familiar to many developers, Sagas/Generators are more powerful but you will need to learn them. But both middleware can coexist, so you can start with Thunks and introduce Sagas when/if you need them.

80
Q

What is Redux DevTools?

A

Redux DevTools is a live-editing time travel environment for Redux with hot reloading, action replay, and customizable UI. If you don’t want to bother with installing Redux DevTools and integrating it into your project, consider using Redux DevTools Extension for Chrome and Firefox.

81
Q

What are the features of Redux DevTools?

A

Some of the main features of Redux DevTools are below,

[1] Lets you inspect every state and action payload.
[2] Lets you go back in time by cancelling actions.
[3] If you change the reducer code, each staged action will be re-evaluated.
[4] If the reducers throw, you will see during which action this happened, and what the error was.
[5] With persistState() store enhancer, you can persist debug sessions across page reloads.

82
Q

What are Redux selectors and why to use them?

A

Selectors are functions that take Redux state as an argument and return some data to pass to the component.

For example, to get user details from the state:

const getUserData = state => state.user.data

These selectors have two main benefits,

[1] The selector can compute derived data, allowing Redux to store the minimal possible state

[2] The selector is not recomputed unless one of its arguments changes

83
Q

What is Redux Form?

A

Redux Form works with React and Redux to enable a form in React to use Redux to store all of its state. Redux Form can be used with raw HTML5 inputs, but it also works very well with common UI frameworks like Material UI, React Widgets and React Bootstrap.

84
Q

What are the main features of Redux Form?

A

Some of the main features of Redux Form are:

[1] Field values persistence via Redux store.
[2] Validation (sync/async) and submission.
[3] Formatting, parsing and normalization of field values.

85
Q

How to add multiple middlewares to Redux?

A

You can use applyMiddleware().

For example, you can add redux-thunk and logger passing them as arguments to applyMiddleware():

import { createStore, applyMiddleware } from 'redux' 
const createStoreWithMiddleware = applyMiddleware(ReduxThunk, logger)(createStore)
86
Q

How to set initial state in Redux?

A

You need to pass initial state as second argument to createStore:

const rootReducer = combineReducers({ 
 todos: todos, 
 visibilityFilter: visibilityFilter 
}) 
const initialState = { 
 todos: [{ id: 123, name: 'example', completed: false }] 
} 

const store = createStore(
rootReducer,
initialState
)

87
Q

How Relay is different from Redux?

A

Relay is similar to Redux in that they both use a single store. The main difference is that relay only manages state originated from the server, and all access to the state is used via GraphQL queries (for reading data) and mutations (for changing data). Relay caches the data for you and optimizes data fetching for you, by fetching only changed data and nothing more.

88
Q

What is an action in Redux?

A

Actions are plain JavaScript objects or payloads of information that send data from your application to your store. They are the only source of information for the store. Actions must have a type property that indicates the type of action being performed.

For example, let’s take an action which represents adding a new todo item:

{
type: ADD_TODO,
text: ‘Add todo item’
}

89
Q

What is the difference between React Native and React?

A

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.

90
Q

How to test React Native apps?

A

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.

91
Q

How to do logging in React Native?

A

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

92
Q

How to debug your React Native?

A

Follow the below steps to debug React Native app:

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

93
Q

What is reselect and how it works?

A

Reselect is a selector library (for Redux) which uses memoization concept. It was originally written to compute derived data from Redux-like applications state, but it can’t be tied to any architecture or library.

Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes. If the the same inputs are provided twice in a row, Reselect returns the cached output. It’s memoization and cache are fully customizable.

94
Q

What is Flow?

A

Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.

95
Q

What is the difference between Flow and PropTypes?

A

Flow is a static analysis tool (static checker) which uses a superset of the language, allowing you to add type annotations to all of your code and catch an entire class of bugs at compile time.

PropTypes is a basic type checker (runtime checker) which has been patched onto React. It can’t check anything other than the types of the props being passed to a given component. If you want more flexible typechecking for your entire project Flow/TypeScript are appropriate choices.

96
Q

How to use Font Awesome icons in React?

A

The below steps followed to include Font Awesome in React:

Install font-awesome:

$ npm install –save font-awesome
Import font-awesome in your index.js file:

import ‘font-awesome/css/font-awesome.min.css’
Add Font Awesome classes in className:

render() {
return

}

97
Q

What is React Dev Tools?

A

React Developer Tools let you inspect the component hierarchy, including component props and state. It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native).

The official extensions available for different browsers or environments.

Chrome extension
Firefox extension
Standalone app (Safari, React Native, etc)

98
Q

Why is DevTools not loading in Chrome for local files?

A

If you opened a local HTML file in your browser (file://…) then you must first open Chrome Extensions and check Allow access to file URLs.

99
Q

How to use Polymer in React?

A

You need to follow below steps to use Polymer in React,

[1] Create a Polymer element:

Polymer({
is: ‘calender-element’,
ready: function() {
this.textContent = ‘I am a calender’
}
})

[2] Create the Polymer component HTML tag by importing it in a HTML document, e.g. import it in the index.html of your React application:

[3] Use that element in the JSX file:

import React from ‘react’

class MyComponent extends React.Component { 
 render() { 
 return ( 

)
}
}

export default MyComponent

100
Q

What are the advantages of React over Vue.js?

A

React has the following advantages over Vue.js:

Gives more flexibility in large apps developing.
Easier to test.
Suitable for mobile apps creating.
More information and solutions available.

Note: The above list of advantages are purely opinionated and it vary based on the professional experience. But they are helpful as base parameters.

101
Q

What is the difference between React and Angular?

A

Let’s see the difference between React and Angular in a table format.