Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Title: Reactjs Interview Questions Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side
Questions Core React What is React? What are the major features of React? What is JSX? What is the difference between Element and Component? How to create components in React? When to use a Class Component over a Function Component? What are Pure Components? What is state in React? What are props in React? What is the difference between state and props? Why should we not update the state directly? What is the purpose of callback function as an argument of setState()? What is the difference between HTML and React event handling? How to bind methods or event handlers in JSX callbacks? How to pass a parameter to an event handler or callback? What are synthetic events in React? What are inline conditional expressions? What is “key” prop and what is the benefit of using it in arrays of elements? What is the use of refs? How to create refs? What are forward refs? 1
No
...
Questions
60 61 62 63 64 65
How to use InnerHtml in React? How to use styles in React? How events are different in React? What will happen if you use setState in constructor? What is the impact of indexes as keys? Is it good to use setState() in componentWillMount() method? What will happen if you use props in initial state? How do you conditionally render components? Why we need to be careful when spreading props on DOM elements?? How you use decorators in React? How do you memoize a component? How you implement Server-Side Rendering or SSR? How to enable production mode in React? What is CRA and its benefits? What is the lifecycle methods order in mounting? What are the lifecycle methods going to be deprecated in React v16? What is the purpose of getDerivedStateFromProps() lifecycle method? What is the purpose of getSnapshotBeforeUpdate() lifecycle method? Do Hooks replace render props and higher order components? What is the recommended way for naming components? What is the recommended ordering of methods in component class? What is a switching component? Why we need to pass a function to setState()? What is strict mode in React? What are React Mixins? Why is isMounted() an anti-pattern and what is the proper solution? What are the Pointer Events supported in React? Why should component names start with capital letter? Are custom DOM attributes supported in React v16? What is the difference between constructor and getInitialState? Can you force a component to re-render without calling setState? What is the difference between super() and super(props) in React using ES6 classes? How to loop inside JSX?
Questions React Router What is React Router? How React Router is different from history library? What are the components of React Router v4? What is the purpose of push and replace methods of history? How do you programmatically navigate using React router v4? How to get query parameters in React Router v4 Why you get “Router may have only one child element” warning? How to pass params to history
...
Questions
162 163 164
How to use connect from React Redux? How to reset state in Redux? Whats the purpose of at symbol in the redux connect decorator? What is the difference between React context and React Redux? Why are Redux state functions called reducers? How to make AJAX request in Redux? Should I keep all component’s state in Redux store? What is the proper way to access Redux store? What is the difference between component and container in React Redux? What is the purpose of the constants in Redux? What are the different ways to write mapDispatchToProps()? What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()? How to structure Redux top level directories? What is redux-saga? What is the mental model of redux-saga? What are the differences between call and put in redux-saga What is Redux Thunk? What are the differences between redux-saga and redux-thunk What is Redux DevTools? What are the features of Redux DevTools? What are Redux selectors and Why to use them? What is Redux Form? What are the main features of Redux Form? How to add multiple middlewares to Redux? How to set initial state in Redux? How Relay is different from Redux? What is an action in Redux? React Native What is the difference between React Native and React? How to test React Native apps? How to do logging in React Native? How to debug your React Native? React supported libraries and Integration What is reselect and how it works? What is Flow? What is the difference between Flow and PropTypes?
No
...
js? What is the difference between React and Angular? Why React tab is not showing up in DevTools? What are styled components? Give an example of Styled Components? What is Relay? How to use TypeScript in create-react-app application? Miscellaneous What are the main features of reselect library? Give an example of reselect usage? Does the statics object work with ES6 classes in React? Can Redux only be used with React? Do you need to have a particular build tool to use Redux? How Redux Form initialValues get updated from state? How React PropTypes allow different type for one prop? Can I import an SVG file as react component? Why are inline ref callbacks or functions not recommended? What is render hijacking in React? What are HOC factory implementations? How to pass numbers to React component? Do I need to keep all my state into Redux? Should I ever use react internal state? What is the purpose of registerServiceWorker in React? What is React memo function? What is React lazy function? How to prevent unnecessary updates using setState? How do you render Array, Strings and Numbers in React 16 Version? How to use class field declarations syntax in React classes? What are hooks? What rules need to be followed for hooks? How to ensure hooks followed the rules in your project? What are the differences between Flux and Redux? What are the benefits of React Router V4? Can you describe about componentDidCatch lifecycle method signature?
What are the conditions to safely use the index as a key? Is it keys should be globally unique? What is the popular choice for form handling? What are the advantages of formik over redux form library? Why do you not required to use inheritance? Can I use web components in react application? What is dynamic import? What are loadable components? What is suspense component? What is route based code splitting? Give an example on How to use context? What is the purpose of default value in context? How do you use contextType? What is a consumer? How do you solve performance corner cases while using context? What is the purpose of forward ref in HOCs? Is it ref argument available for all functions or class components? Why do you need additional care for component libraries while using forward refs? How to create react class components without ES6? Is it possible to use react without JSX? What is diffing algorithm? What are the rules covered by diffing algorithm? When do you need to use refs? Is it prop must be named as render for render props? What are the problems of using render props with pure components? How do you create HOC using render props? What is windowing technique? How do you print falsy values in JSX? What is the typical use case of portals? How do you set default value for uncontrolled component? What is your favorite React stack? What is the difference between Real DOM and Virtual DOM? How to add Bootstrap to a react application? Can you list down top websites or applications using react as front end framework? Is it recommended to use CSS In JS technique in React?
No
...
9? What is the purpose of eslint plugin for hooks? What is the difference between Imperative and Declarative in React? What are the benefits of using typescript with reactjs? How do you make sure that user remains authenticated on page refresh while using Context API State Management? What are the benefits of new JSX transform? How does new JSX transform different from old transform? How do you get redux scaffolding using create-react-app? What are React Server components? What is prop drilling? What is state mutation and how to prevent it? What is the difference between useState and useRef hook?
Core React 1
...
It is used for handling view layer for web and mobile apps
...
React was first deployed on Facebook’s News Feed in 2011 and on Instagram in 2012
...
What are the major features of React? The major features of React are: • It uses VirtualDOM instead of RealDOM considering that RealDOM manipulations are expensive
...
• Follows Unidirectional data flow or data binding
...
� Back to Top 3
...
Basically it just provides syntactic sugar for the React
...
In the example below text inside
tag is returned as JavaScript function to the render function
...
Component { render() { return(
{'Welcome to React world!'}
) } } � Back to Top 4
...
Elements can 11
contain other Elements in their props
...
Once an element is created, it is never mutated
...
createElement( 'div', {id: 'login-btn'}, 'Login' ) The above React
...
render():
Login
Whereas a component can be declared in several different ways
...
In either case, it takes props as an input, and returns a JSX tree as the output: const Button = ({ onLogin }) =>
Login
Then JSX gets transpiled to a React
...
createElement( 'div', { id: 'login-btn', onClick: onLogin }, 'Login' ) � Back to Top 5
...
1
...
Those are pure JavaScript functions that accept props object as the first parameter and return React elements:
12
“jsx harmony function Greeting({ message }) {
{Hello, ${message}‘}
return
} “‘ 2
...
The above function component can be written as: jsx harmony render() { } }
class Greeting extends React
...
props
...
When to use a Class Component over a Function Component? If the component needs state or lifecycle methods then use class component otherwise use function component
...
8 with the addition of Hooks, you could use state , lifecycle methods and other features that were only available in class component right in your function component
...
What are Pure Components? React
...
Component except that it handles the shouldComponentUpdate() method for you
...
Component on the other hand won’t compare current props and state to next out of the box
...
� Back to Top 8
...
We should always try to make our state as simple as possible and minimize the number of stateful components
...
Component { constructor(props) { super(props) this
...
state
...
e
...
� Back to Top 9
...
They are single values or objects containing a set of values that are passed to components on creation using a naming convention similar to HTML-tag attributes
...
14
The primary purpose of props in React is to provide following component functionality: 1
...
2
...
3
...
props
...
For example, let us create an element with reactProp property: jsx harmony
This reactProp (or whatever you came up with) name then becomes a property attached to React’s native props object which originally already exists on all components created using React library
...
reactProp � Back to Top 10
...
While both of them hold information that influences the output of render, they are different in their functionality with respect to component
...
� Back to Top 11
...
//Wrong this
...
message = 'Hello world' Instead use setState() method
...
When state changes, the component responds by rerendering
...
setState({ message: 'Hello World' }) Note: You can directly assign to the state object either in constructor or using latest javascript’s class field declaration syntax
...
What is the purpose of callback function as an argument of setState()? The callback function is invoked when setState finished and the component gets rendered
...
Note: It is recommended to use lifecycle method rather than this callback function
...
log('The name has updated and component re-ren � Back to Top 13
...
In HTML, the event name usually represents in lowercase as a convention:
{'Click
3
...
jsx harmony handleClick() { console
...
handleClick()}>Click Me; } Note: If the callback is passed as prop to child components, those components might do an extra re-rendering
...
bind() or public class fields syntax approach considering performance
...
How to pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters:
17
jsx harmony this
...
bind: jsx harmony
...
bind(this, id)} /> Apart from these two approaches, you can also pass arguments to a function which is defined as arrow function jsx harmony onClick={this
...
log("Hello, your ticket number is", id) }; � Back to Top 16
...
Its API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers
...
What are inline conditional expressions? You can use either if statements or ternary expressions which are available from JS to conditionally render expressions
...
jsx harmony
Hello!
{ !isLogin?
unread messages
...
messages
...
length} :
You
}
� Back to Top 18
...
Key prop helps React identify which items have changed, are added, or are removed
...
map((todo) => key={todo
...
text} ) 18
When you don’t have stable IDs for rendered items, you may use the item index as a key as a last resort: jsx harmony const todoItems = todos
...
text} ) Note: 1
...
This can negatively impact performance and may cause issues with component state
...
If you extract list item as separate component then apply keys on list component instead of li tag
...
There will be a warning message in the console if the key prop is not present on list items
...
What is the use of refs? The ref is used to return a reference to the element
...
� Back to Top 20
...
This is a recently added approach
...
createRef() method and attached to React elements via the ref attribute
...
For example, the search bar component’s input element is accessed as follows, jsx harmony class SearchBar extends Component { constructor(props) { super(props); this
...
state = { term: '' }; this
...
txtSearch = e; } } onInputChange(event) {
19
this
...
txtSearch
...
onInputChange
...
state ref={this
...
Note: You can also use inline ref callbacks even though it is not a recommended approach
...
What are forward refs? Ref forwarding is a feature that lets some components take a ref they receive, and pass it further down to a child
...
forwardRef((props, ref) => ( {props
...
createRef(); {‘Forward Ref’} “‘ � Back to Top 22
...
Because findDOMNode() prevents certain improvements in React in the future
...
scrollIntoView() } render() { return } } The recommended approach is: class MyComponent extends Component { constructor(props){ super(props); this
...
node
...
scrollIntoView(); } render() { return
...
Why are String Refs legacy? If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like ref={'textInput'}, and the DOM node is accessed as this
...
textInput
...
String refs were removed in React v16
...
They force React to keep track of currently executing component
...
2
...
Callback refs are perfectly composable
...
They don’t work with static analysis like Flow
...
refs, as well as its type (which could be different)
...
4
...
g
...
Ref will get attached to DataTable rather than MyComponent: return ; // This would work though! Callback refs are awesome
...
21
What is Virtual DOM? The Virtual DOM (VDOM) is an in-memory representation of Real DOM
...
It’s a step that happens between the render function being called and the displaying of elements on the screen
...
� Back to Top 25
...
1
...
Figure 2: vdom 2
...
3
...
� Back to Top 26
...
The Virtual DOM is a concept implemented by libraries in JavaScript on top of browser APIs
...
22
Figure 3: vdom2
Figure 4: vdom3
23
What is React Fiber? Fiber is the new reconciliation engine or reimplementation of core algorithm in React v16
...
� Back to Top 28
...
Its headline feature is incremental rendering: the ability to split rendering work into chunks and spread it out over multiple frames
...
Ability to split interruptible work in chunks
...
Ability to prioritize, rebase and reuse work in progress
...
Ability to yield back and forth between parents and children to support layout in React
...
Ability to return multiple elements from render()
...
Better support for error boundaries
...
What are controlled components? A component that controls the input elements within the forms on subsequent user input is called Controlled Component, i
...
For example, to write all the names in uppercase letters, we use handleChange as below, handleChange(event) { this
...
target
...
toUpperCase()}) } � Back to Top 30
...
This is a bit more like traditional HTML
...
“‘jsx harmony class UserProfile extends React
...
handleSubmit = this
...
bind(this) this
...
createRef() } handleSubmit(event) { alert(‘A name was submitted:’ + this
...
current
...
preventDefault() } render() { return ( {‘Name:’} ); } } “‘ In most cases, it’s recommend to use controlled components to implement forms
...
The alternative is uncontrolled components, where form data is handled by the DOM itself
...
What is the difference between createElement and cloneElement? JSX elements will be transpiled to React
...
Whereas cloneElement is used to clone an element and pass it new props
...
What is Lifting State Up in React? When several components need to share the same changing data then it is recommended to lift the shared state up to their closest common ancestor
...
� Back to Top
25
33
...
Mounting: The component is ready to mount in the browser DOM
...
2
...
This phase covers getDerivedStateFromProps(), shouldComponentUpdate(), render(), getSnapshotBeforeUpdate() and componentDidUpdate() lifecycle methods
...
Unmounting: In this last phase, the component is not needed and gets unmounted from the browser DOM
...
It’s worth mentioning that React internally has a concept of phases when applying changes to the DOM
...
Render The component will render without any side effects
...
2
...
3
...
React 16
...
3 � Back to Top 34
...
3 • componentWillMount: Executed before rendering and is used for App level configuration in your root component
...
4+
Figure 6: phases 16
...
• componentWillReceiveProps: Executed when particular prop updates to trigger state transitions
...
By default it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives new prop
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
React 16
...
This exists for rare use cases where you need a derived state
...
• componentDidMount: Executed after first rendering and where all AJAX requests, DOM or state updates, and set up event listeners should occur
...
By default, it returns true
...
It is a great place to improve performance as it allows you to prevent a re-render if component receives a new prop
...
Any value returned by this will be passed into componentDidUpdate()
...
e
...
• componentDidUpdate: Mostly it is used to update the DOM in response to prop or state changes
...
• componentWillUnmount It will be used to cancel any outgoing network requests, or remove all event listeners associated with the component
...
28
What are Higher-Order Components? A higher-order component (HOC) is a function that takes a component and returns a new component
...
We call them pure components because they can accept any dynamically provided child component but they won’t modify or copy any behavior from their input components
...
2
...
4
...
Render hijacking
...
Props manipulation
...
How to create props proxy for HOC component? You can add/edit props passed to the component using props proxy pattern like this: “‘jsx harmony function HOC(WrappedComponent) { return class Test extends Component { render() { const newProps = { title: ‘New Header’, footer: false, showFeatureX: false, showFeatureY: true } return
...
props} {
...
What is context? Context provides a way to pass data through the component tree without having to pass props down manually at every level
...
const {Provider, Consumer} = React
...
29
What is children prop? Children is a prop (this
...
children) that allows you to pass components as data to other components, just like any other prop you use
...
There are several methods available in the React API to work with this prop
...
Children
...
Children
...
Children
...
Children
...
Children
...
A simple usage of children prop looks as below, “‘jsx harmony const MyDiv = React
...
props
...
render( {‘Hello’} {‘World’} , node ) “‘ � Back to Top 39
...
Single-line comments: jsx harmony
{/* Single-line comments(In vanilla JavaScript, the single-line comments are represented by double slash(//)) */} {`Welcome ${user}, let's play React`}
Multi-line comments: jsx harmony
{/* Multi-line comments for more than one line */} {`Welcome ${user}, let's play React`}
� Back to Top 40
...
The same applies to ES6 sub-classes as well
...
props in your child constructors
...
Component { constructor(props) { super(props) console
...
props) // prints { name: 'John', age: 42 } } } Not passing props: class MyComponent extends React
...
log(this
...
log(props) // prints { name: 'John', age: 42 } } render() { // no difference outside constructor console
...
props) // prints { name: 'John', age: 42 } } } The above code snippets reveals that this
...
It would be the same outside the constructor
...
What is reconciliation? When a component’s props or state change, React decides whether an actual DOM update is necessary by comparing the newly returned element with the previously rendered one
...
This process is called reconciliation
...
How to set state with a dynamic key name? If you are using ES6 or the Babel transpiler to transform your JSX code then you can accomplish this with computed property names
...
setState({ [event
...
id]: event
...
value }) } � Back to Top 43
...
jsx harmony render() { // Wrong: handleClick is called instead of passed as a reference! return
...
handleClick}>{'Click Me'} } � Back to Top 44
...
lazy function supports default exports only
...
It also ensures that tree shaking keeps working and don’t pull unused components
...
js export const SomeComponent = /*
...
*/; and reexport MoreComponents
...
js javascript // IntermediateComponent
...
/MoreComponents
...
/IntermediateComponent
...
32
Why React uses className over class attribute? class is a keyword in JavaScript, and JSX is an extension of JavaScript
...
Pass a string as the className prop
...
What are fragments? It’s a common pattern in React which is used for a component to return multiple elements
...
jsx harmony render() { return (
...
Fragment> ) } There is also a shorter syntax, but it’s not supported in many tools: jsx harmony render() { return ( >
<> ) }
� Back to Top 47
...
Fragments are a bit faster and use less memory by not creating an extra DOM node
...
2
...
3
...
� Back to Top 48
...
33
ReactDOM
...
The second argument is a DOM element
...
What are stateless components? If the behaviour is independent of its state then it can be a stateless component
...
But unless you need to use a lifecycle hook in your components, you should go for function components
...
� Back to Top 50
...
These stateful components are always class components and have a state that gets initialized in the constructor
...
state = { count: 0 } } render() { //
...
8 Update: Hooks let you use state and other React features without writing classes
...
How to apply validation on props in React? When the application is running in development mode, React will automatically check all props that we set on components to make sure they have correct type
...
It’s disabled in production mode due to performance impact
...
We can define propTypes for User component as below: “‘jsx harmony import React from ‘react’ import PropTypes from ‘proptypes’ class User extends React
...
string
...
number
...
props
...
props
...
5 *PropTypes* were moved from `React
...
propTypes = { name: PropTypes
...
isRequired, age: PropTypes
...
isRequired } � Back to Top 52
...
2
...
4
...
JSX makes code easy to read and write
...
Easy to integrate with frameworks (Angular, Backbone) since it is only a view library
...
Easy to write unit and integration tests with tools such as Jest
...
What are the limitations of React? Apart from the advantages, there are few limitations of React too, 1
...
2
...
3
...
4
...
36
5
...
� Back to Top 54
...
A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info) or static getDerivedStateFromError(): “‘jsx harmony class ErrorBoundary extends React
...
state = { hasError: false } } componentDidCatch(error, info) { // You can also log the error to an error reporting service logErrorToMyService(error, info) } static getDerivedStateFromError(error) { // Update state so the next render will show the fallback UI
...
state
...
’} } return this
...
children }} After that use it as a regular component: ```jsx harmony
� Back to Top 55
...
It has been renamed to componentDidCatch in React v16
...
What are the recommended ways for static type checking? Normally we use PropTypes library (React
...
5) for type checking in the React applications
...
� Back to Top 57
...
Most of the components are not required to use this module
...
� Back to Top 58
...
If the React element was previously rendered into container, it will perform an update on it and only mutate the DOM as necessary to reflect the latest changes
...
render(element, container, [callback]) If the optional callback is provided, it will be executed after the component is rendered or updated
...
What is ReactDOMServer? The ReactDOMServer object enables you to render components to static markup (typically used on node server)
...
The following methods can be used in both the server and browser environments: 1
...
renderToStaticMarkup() For example, you generally run a Node-based web server like Express, Hapi, or Koa, and you call renderToString to render your root component to a string, which you then send as response
...
/MyPage' app
...
write('My Page') res
...
write(renderToString()) res
...
end() }) � Back to Top 60
...
Just like innerHTML, it is risky to use this attribute considering cross-site scripting (XSS) attacks
...
In this example MyComponent uses dangerouslySetInnerHTML attribute for setting HTML markup: “‘jsx harmony function createMarkup() { return { __html: ‘First · Second’ } } function MyComponent() { return } “‘ � Back to Top 61
...
This is consistent with the DOM style JavaScript property, is more efficient, and prevents XSS security holes
...
g
...
style
...
� Back to Top 62
...
React event handlers are named using camelCase, rather than lowercase
...
With JSX you pass a function as the event handler, rather than a string
...
What will happen if you use setState() in constructor? When you use setState(), then apart from assigning to the object state React also re-renders the component and all its children
...
So we need to use this
...
� Back to Top 64
...
In the below code snippet each element’s key will be based on ordering, rather than tied to the data that is being represented
...
jsx harmony {todos
...
todo}
If you use element data for unique key, assuming todo
...
jsx harmony {todos
...
todo}
key={todo
...
Is it good to use setState() in componentWillMount() method? Yes, it is safe to use setState() inside componentWillMount() method
...
componentWillMount() is invoked immediately before mounting occurs
...
Avoid introducing any side-effects or subscriptions in this method
...
jsx harmony componentDidMount() { axios
...
then((result) => { this
...
result
...
What will happen if you use props in initial state? If the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component
...
The below component won’t display the updated input value: “‘jsx harmony class MyComponent extends React
...
state = { records: [], inputValue: this
...
inputValue }; } render() { return
41
{this
...
inputValue} }} Using props inside render method will update the value: ```jsx harmony class MyComponent extends React
...
state = { record: [] } } render() { return
{this
...
inputValue}
} } � Back to Top 67
...
JSX does not render false or undefined, so you can use conditional short-circuiting to render a given part of your component only if a certain condition is true
...
) � Back to Top 68
...
Instead we can use prop destructuring 42
with
...
For example, “‘jsx harmony const ComponentA = () => const ComponentB = ({ isDisplay, …domProps }) =>
{‘ComponentB’} “‘ � Back to Top 69
...
Decorators are flexible and readable way of modifying component functionality
...
Component { //…
...
Component { componentDidMount() { document
...
this
...
� Back to Top 70
...
For example moize library can memoize the component in another component
...
/components/Component’ // this module exports a non-memoized component
How you implement Server Side Rendering or SSR? React is already equipped to handle rendering on Node servers
...
“‘jsx harmony import ReactDOMServer from ‘react-dom/server’ import App from ‘
...
renderToString() “‘ This method will output the regular HTML as a string, which can be then placed inside a page body as part of the server response
...
� Back to Top 72
...
Apart from this, if you minify the code, for example, Uglify’s dead-code elimination to strip out development only code and comments, it will drastically reduce the size of your bundle
...
44
What is CRA and its benefits? The create-react-app CLI tool allows you to quickly create & run React applications with no configuration step
...
2
...
4
...
Language extras beyond ES6 like the object spread operator
...
A fast interactive unit test runner with built-in support for coverage reporting
...
A live development server that warns about common mistakes
...
A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps
...
What is the lifecycle methods order in mounting? The lifecycle methods are called in the following order when an instance of a component is being created and inserted into the DOM
...
2
...
4
...
45
What are the lifecycle methods going to be deprecated in React v16? The following lifecycle methods going to be unsafe coding practices and will be more problematic with async rendering
...
componentWillMount() 2
...
componentWillUpdate() Starting with React v16
...
� Back to Top 76
...
It can return an object to update state, or null to indicate that the new props do not require any state updates
...
Component { static getDerivedStateFromProps(props, state) { //
...
� Back to Top 77
...
The return value from this method will be passed as the third parameter to componentDidUpdate()
...
Component { getSnapshotBeforeUpdate(prevProps, prevState) { //
...
� Back to Top 78
...
� Back to Top 79
...
Using displayName for naming component: export default React
...
}) The recommended approach: export default class TodoApp extends React
...
} also const TodoApp = () => { //
...
What is the recommended ordering of methods in component class? Recommended ordering of methods from mounting to render stage: 1
...
constructor() 47
3
...
5
...
7
...
9
...
11
...
getter methods for render like getSelectReason() or getFooterContent() 13
...
render() � Back to Top 81
...
We need to use object to map prop values to components
...
/HomePage’ import AboutPage from ‘
...
/ServicesPage’ import ContactPage from ‘
...
page] || ContactPage return } // The keys of the PAGES object can be used in the prop types to catch dev-time errors
...
propTypes = { page: PropTypes
...
keys(PAGES))
...
Why we need to pass a function to setState()? The reason behind for this is that setState() is an asynchronous operation
...
That means you
48
should not rely on the current state when calling setState() since you can’t be sure what that state will be
...
By doing this you can avoid issues with the user getting the old state value on access due to the asynchronous nature of setState()
...
After three consecutive increment operations, the value is going to be incremented only by one
...
state
...
setState({ count: this
...
count + 1 }) this
...
state
...
setState({ count: this
...
count + 1 }) // this
...
count === 1, not 3 If we pass a function to setState(), the count gets incremented correctly
...
setState((prevState, props) => ({ count: prevState
...
increment })) // this
...
count === 3 as expected (OR) Why function is preferred over object for setState()? React may batch multiple setState() calls into a single update for performance
...
props and this
...
This counter example will fail to update as expected: // Wrong this
...
state
...
props
...
That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument
...
setState((prevState, props) => ({ counter: prevState
...
increment })) � Back to Top 83
...
StrictMode is a useful component for highlighting potential problems in an application
...
It activates additional checks and warnings for its descendants
...
“‘jsx harmony import React from ‘react’ function ExampleApplication() { return (
...
StrictMode>
) } “‘ In the example above, the strict mode checks apply to and components only
...
What are React Mixins? Mixins are a way to totally separate components to have a common functionality
...
One of the most commonly used mixins is PureRenderMixin
...
createClass({ mixins: [PureRenderMixin], //
...
50
Why is isMounted() an anti-pattern and what is the proper solution? The primary use case for isMounted() is to avoid calling setState() after a component has been unmounted, because it will emit a warning
...
isMounted()) { this
...
}) } Checking isMounted() before calling setState() does eliminate the warning, but it also defeats the purpose of the warning
...
An optimal solution would be to find places where setState() might be called after a component has unmounted, and fix them
...
Ideally, any callbacks should be canceled in componentWillUnmount(), prior to unmounting
...
What are the Pointer Events supported in React? Pointer Events provide a unified way of handling all input events
...
We need to remember that these events will only work in browsers that support the Pointer Events specification
...
2
...
4
...
6
...
8
...
10
...
51
Why should component names start with capital letter? If you are rendering your component using JSX, the name of that component has to begin with a capital letter otherwise React will throw an error as an unrecognized tag
...
jsx harmony class SomeComponent extends Component { // Code goes here } You can define component class which name starts with lowercase letter, but when it’s imported it should have capital letter
...
/MyComponent' What are the exceptions on React component naming? The component names should start with an uppercase letter but there are few exceptions to this convention
...
For example, the below tag can be compiled to a valid component, jsx harmony render() { return ( // `React
...
component)`
...
Are custom DOM attributes supported in React v16? Yes
...
If you wrote JSX with an attribute that React doesn’t recognize, React would just skip it
...
� Back to Top 89
...
createClass()
...
Component { constructor(props) { super(props) this
...
createClass(): const MyComponent = React
...
createClass() is deprecated and removed in React v16
...
� Back to Top 90
...
If your render() method depends on some other data, you can tell React that the component needs re-rendering by calling forceUpdate()
...
forceUpdate(callback) It is recommended to avoid all uses of forceUpdate() and only read from this
...
state in render()
...
53
What is the difference between super() and super(props) in React using ES6 classes? When you want to access this
...
Using super(props): class MyComponent extends React
...
log(this
...
} } } Using super(): class MyComponent extends React
...
log(this
...
props
...
How to loop inside JSX? You can simply use Array
...
map with ES6 arrow function syntax
...
map(item => key={item
...
name} />)} But you can’t iterate using for loop: jsx harmony for (let i = 0; i < items
...
id} name={items[i]
...
This may change thanks to do expressions which are stage 1 proposal
...
How do you access props in attribute quotes? React (or JSX) doesn’t support variable interpolation inside an attribute value
...
props
...
So the below expression works: jsx harmony
...
image} /> Using template strings will also work: jsx harmony
...
image}`} /> � Back to Top 94
...
PropTypes
...
PropTypes
...
ReactComponent
...
PropTypes
...
PropTypes
...
PropTypes
...
isRequired, fontSize: React
...
number
...
isRequired } � Back to Top 95
...
jsx harmony
Instead you need to move curly braces outside (don’t forget to include spaces between class names):
55
jsx harmony
...
visible ? 'show' : 'hidden')}> Template strings will also work: jsx harmony
...
visible ? 'show' : 'hidden'}`}> � Back to Top 96
...
createElement(), React
...
Children, and other helpers related to elements and component classes
...
The react-dom package contains ReactDOM
...
renderToString() and ReactDOMServer
...
� Back to Top 97
...
React v0
...
By looking at some of the packages, react-native, react-art, react-canvas, and react-three, it has become clear that the beauty and essence of React has nothing to do with browsers or the DOM
...
This paves the way to writing components that can be shared between the web version of React and React Native
...
How to use React label element? If you try to render a
) }} ReactDOM
...
getElementById(‘app’)) Also in Functional component (react 16
...
current
...
render(, document
...
What are the possible ways of updating objects in state? 1
...
assign() to create a copy of the object: const user = Object
...
state
...
setState({ user }) • Using spread operator: const user = {
...
state
...
setState({ user }) 2
...
setState(prevState => ({ user: {
...
user, age: 42 } })) � Back to Top 110
...
version to get the version
...
version ReactDOM
...
getElementById(‘app’) ) “‘ � Back to Top 111
...
Manual import from core-js: Create a file called (something like) polyfills
...
js file
...
import 'core-js/fn/array/find' import 'core-js/fn/array/includes' import 'core-js/fn/number/is-nan' 2
...
io CDN to retrieve custom, browser-specific polyfills by adding this line to index
...
polyfill
...
min
...
prot In the above script we had to explicitly request the Array
...
includes feature as it is not included in the default feature set
...
How to use https instead of http in create-react-app? You just need to use HTTPS=true configuration
...
json scripts section:
You can edit your
"scripts": { "start": "set HTTPS=true && react-scripts start" } or just run set HTTPS=true && npm start � Back to Top 113
...
env in the project root and write the import path: NODE_PATH=src/app After that restart the development server
...
� Back to Top 114
...
listen(function (location) { window
...
pathname + location
...
ga('send', 'pageview', location
...
search) }) � Back to Top 115
...
componentDidMount() { this
...
setState({ time: Date
...
interval) } � Back to Top 116
...
You need to add vendor prefixes manually
...
How to import and export components using React and ES6? You should use default for exporting the components “‘jsx harmony import React from ‘react’ import User from ‘user’ export default class MyProfile extends React
...
� Back to Top 119
...
� Back to Top 120
...
class MyComponent extends React
...
How to programmatically trigger click event in React? 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
...
This can be done in two steps: 1
...
inputElement =
2
...
inputElement
...
64
Is it possible to use async/await in plain React? If you want to use async/await in React, you will need Babel and transform-async-to-generator plugin
...
� Back to Top 123
...
1
...
common/ �� Avatar
...
css �� APIUtils
...
test
...
js �� Feed
...
css �� FeedStory
...
test
...
js profile/ �� index
...
js �� ProfileHeader
...
css �� ProfileAPI
...
Grouping by file type: Another popular way to structure projects is to group similar files together
...
js �� APIUtils
...
js �� ProfileAPI
...
js components/ �� Avatar
...
css Feed
...
css FeedStory
...
test
...
js ProfileHeader
...
css
� Back to Top 124
...
� Back to Top 125
...
Any values that are likely to be used across different UI components should be extracted into their own modules
...
/styles' � Back to Top 126
...
There are plugins available that analyse specific code styles
...
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
...
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 to make AJAX call and in which component lifecycle methods should I make an AJAX call? You can use AJAX libraries such as Axios, jQuery AJAX, and the browser built-in fetch
...
This is so you can use setState() to update your component when the data is retrieved
...
Component { constructor(props) { super(props) this
...
example
...
then(res => res
...
then( (result) => { this
...
employees }) }, (error) => { this
...
state if (error) { return Error: {error
...
map(employee => ( {employee
...
experience} ))} ) } } } “‘ � Back to Top
67
128
...
The below component uses render prop which returns a React element
...
target}`} )}/>
{`Hello
Libraries such as React Router and DownShift are using this pattern
...
What is React Router? 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 React Router is different from history library? React Router is a wrapper around the history library which handles interaction with the browser’s window
...
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
...
What are the components of React Router v4? React Router v4 provides below 3 components: 1
... 3
...
React Router v4 makes the properties and methods of the
68
history instance associated with your router available through the context in the router object
...
What is the purpose of push() and replace() methods of history? A history instance has two methods for navigation purpose
...
push() 2
...
� Back to Top 133
...
1
...
This object provides push() and replace() methods to avoid the usage of context
...
push(‘/new-location’) }} > {‘Click Me!’} )) “‘ 2
...
“‘jsx harmony import { Route } from ‘react-router-dom’ const Button = () => ( ( type=‘button’ onClick={() => { history
...
Using context: This option is not recommended and treated as unstable API
...
history
...
contextTypes = { history: React
...
shape({ push: React
...
func
...
How to get query parameters in React Router v4? 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
...
The recommended approach is to use query strings library
...
parse(props
...
search); You can also use URLSearchParams if you want something native: const params = new URLSearchParams(props
...
search) const foo = params
...
� Back to Top 135
...
At first you need to add Switch to your imports: import { Switch, Router, Route } from 'react-router' Then define the routes within block: jsx harmony
...
*/} />
� Back to Top 136
...
push method in React Router v4? While navigating you can pass props to the history object: this
...
history
...
data } }) The search property is used to pass query params in push() method
...
How to implement default or NotFound page? A renders the first child that matches
...
So you just need to simply drop path attribute as below jsx harmony /> � Back to Top 138
...
Create a module that exports a history object and import this module across the project
...
js file: import { createBrowserHistory } from 'history' export default createBrowserHistory({ /* pass a configuration object here if needed */ }) 2
...
Import the above history
...
js file: “‘jsx harmony import { Router } from ‘react-router-dom’ import history from ‘
...
/App’ ReactDOM
...
You can also use push method of history object similar to built-in history object: // some-other-file
...
/history' history
...
How to perform automatic redirect after login? The react-router package provides component in React Router
...
Like server-side redirects, the new location will override the current location in the history stack
...
state
...
What is React Intl? The React Intl 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
...
� Back to Top 141
...
2
...
4
...
6
...
Display numbers with separators
...
Display dates relative to “now”
...
Support for 150+ languages
...
Built on standards
...
What are the two ways of formatting in React Intl? The library provides two ways to format strings, numbers, and dates: 1
...
'} />
defaultMessage={'The
2
...
', } }) formatMessage(messages
...
How to use as placeholder using React Intl? The
...
In that case, you should use lower level API formatMessage()
...
“‘jsx harmony import React from ‘react’ import { injectIntl, intlShape } from ‘react-intl’
How to access current locale with React Intl? You can get the current locale in any component of your application using injectIntl(): “‘jsx harmony import { injectIntl, intlShape } from ‘react-intl’ const MyComponent = ({ intl }) => ( {The current locale is ${intl
...
propTypes = { intl: intlShape
...
How to format date using React Intl? The injectIntl() higher-order component will give you access to the formatDate() method via the props in your component
...
What is Shallow Renderer in React testing? Shallow rendering is useful for writing unit test cases in React
...
For example, if you have the following component: function MyComponent() { return (
{'Title'} {'Description'}
) } Then you can assert as follows: “‘jsx harmony import ShallowRenderer from ‘react-test-renderer/shallow’ // in your test const renderer = new ShallowRenderer() renderer
...
getRenderOutput() expect(result
...
toBe(‘div’) {‘Title’}, {‘Description’}]) “‘
expect(result
...
children)
...
What is TestRenderer package in React? 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
...
What is the purpose of ReactTestUtils package? ReactTestUtils are provided in the with-addons package and allow you to perform actions against a simulated DOM for the purpose of unit testing
...
What is Jest? Jest is a JavaScript unit testing framework created by Facebook based on Jasmine and provides automated mock creation and a jsdom environment
...
� Back to Top 150
...
Automatically mocks dependencies when running your tests
...
Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line
...
� Back to Top 151
...
js file: const sum = (a, b) => a + b export default sum Create a file named sum
...
js which contains actual test:
76
import sum from '
...
toBe(3) }) And then add the following section to your package
...
/sum
...
js � adds 1 + 2 to equal 3 (2ms)
React Redux � Back to Top 152
...
It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow
...
The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:
Figure 7: flux
77
� Back to Top 153
...
Redux can be used together with React, or with any other view library
...
� Back to Top 154
...
Single source of truth: The state of your whole application is stored in an object tree within a single store
...
2
...
This ensures that neither the views nor the network callbacks will ever write directly to the state
...
Changes are made with pure functions: To specify how the state tree is transformed by actions, you write reducers
...
� Back to Top 155
...
Those are as follows: 1
...
You can enforce this with dev-only packages like redux-immutable-state-invariant, Immutable
...
2
...
78
3
...
� Back to Top 156
...
todos, state
...
Redux wraps it in another function that looks like (…args) => dispatch(onTodoClick(…args)), and pass that wrapper function as a prop to your component
...
Can I dispatch an action in reducer? Dispatching an action within a reducer is an anti-pattern
...
Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects
...
How to access Redux store outside a component? You just need to export the store from the module where it created with createStore()
...
store = createStore(myReducer) export default store � Back to Top 159
...
DOM manipulation is very expensive which causes applications to behave slow and inefficient
...
Due to circular dependencies, a complicated model was created around models and views
...
Lot of data changes happens for collaborative applications(like Google Docs)
...
No way to do undo (travel back in time) easily without adding so much extra code
...
Are there any similarities between Redux and RxJS? These libraries are very different for very different purposes, but there are some vague similarities
...
It is usually used as an architecture for UIs
...
RxJS is a reactive programming library
...
Think of it as an alternative to Promises
...
The Store observes actions from a distance, and changes itself
...
� Back to Top 80
161
...
class App extends Component { componentDidMount() { this
...
fetchData() } render() { return this
...
isLoaded ?
How to use connect() from React Redux? You need to follow two steps to use your store in your container: 1
...
2
...
You can import connect() from react-redux
...
Component { render() { return {this
...
containerData} }}
81
function mapStateToProps(state) state
...
How to reset state in Redux? You need to write a root reducer in your application which delegate handling the action to the reducer generated by combineReducers()
...
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
...
type === 'USER_LOGOUT') { state = undefined } return appReducer(state, action) } In case of using redux-persist, you may also need to clean your storage
...
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
...
type === 'USER_LOGOUT') { Object
...
forEach(key => { storage
...
Whats the purpose of at symbol in the Redux connect decorator? The **@** symbol is in fact a JavaScript expression used to signify decorators
...
Let’s take an example setting up Redux without and with a decorator
...
/actionCreators' { bindActionCreators } from 'redux' { connect } from 'react-redux'
function mapStateToProps(state) { return { todos: state
...
Component { //
...
/actionCreators' { bindActionCreators } from 'redux' { connect } from 'react-redux'
function mapStateToProps(state) { return { todos: state
...
Component { //
...
The decorator syntax isn’t built into any JavaScript runtimes yet, and is still experimental and subject to change
...
� Back to Top 165
...
Whereas Redux is much more powerful and provides a large number of features that the Context API doesn’t provide
...
� Back to Top 166
...
Therefore, they act as a reducer of state
...
This state is then reduced (or accumulated) based on the action, and then the next state is returned
...
� Back to Top 167
...
84
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
...
json)) // Use a normal function to set the receive } else { dispatch(someError) } }) } } function setAccount(data) { return { type: 'SET_Account', data: data } } � Back to Top 168
...
� Back to Top 169
...
This pattern is called Higher-Order Components, and is generally the preferred way of extending a component’s functionality in React
...
Let’s take an example of component using connect: import { connect } from 'react-redux' import { setVisibilityFilter } from '
...
/components/Link' const mapStateToProps = (state, ownProps) => ({ 85
class MyComponent { someMethod() { doSomethingWith(this
...
store) } } � Back to Top 170
...
Container is an informal term for a component that is connected to a Redux store
...
� Back to Top 171
...
It also prevents you from introducing silly bugs caused by typos – in which case, you will get a ReferenceError immediately
...
js or actionTypes
...
In Redux, you use them in two places: 1
...
js: import { ADD_TODO } from '
...
In reducers: Let’s create reducer
...
/actionTypes' export default (state = [], action) => { switch (action
...
state, { text: action
...
What are the different ways to write mapDispatchToProps()? There are a few ways of binding action creators to dispatch() in mapDispatchToProps()
...
� Back to Top 173
...
So, if you use a connected component: “‘jsx harmony import ConnectedComponent from ‘
...
� Back to Top 174
...
Components: Used for dumb components unaware of Redux
...
Containers: Used for smart components connected to Redux
...
Actions: Used for all action creators, where file names correspond to part of the app
...
Reducers: Used for all reducers, where files name correspond to state key
...
Store: Used for store initialization
...
� Back to Top
88
175
...
It is available in NPM: $ npm install --save redux-saga � Back to Top 176
...
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
...
What are the differences between call() and put() in reduxsaga? Both call() and put() are effect creator functions
...
put() function creates an effect, which instructs middleware to dispatch an action to the store
...
function* fetchUserSaga(action) { // `call` function accepts rest arguments, which will be passed to `api
...
fetchUser, action
...
� Back to Top 178
...
The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met
...
� Back to Top 179
...
In most of the scenarios, Thunk uses Promises to deal with them, whereas Saga uses Generators
...
But both middleware can coexist, so you can start with Thunks and introduce Sagas when/if you need them
...
What is Redux DevTools? Redux DevTools is a live-editing time travel environment for Redux with hot reloading, action replay, and customizable UI
...
� Back to Top 181
...
Lets you inspect every state and action payload
...
Lets you go back in time by cancelling actions
...
If you change the reducer code, each staged action will be reevaluated
...
If the reducers throw, you will see during which action this happened, and what the error was
...
With persistState() store enhancer, you can persist debug sessions across page reloads
...
What are Redux selectors and why to use them? Selectors are functions that take Redux state as an argument and return some data to pass to the component
...
user
...
The selector can compute derived data, allowing Redux to store the minimal possible state 2
...
What is Redux Form? Redux Form works with React and Redux to enable a form in React to use Redux to store all of its state
...
� Back to Top 184
...
Field values persistence via Redux store
...
Validation (sync/async) and submission
...
Formatting, parsing and normalization of field values
...
How to add multiple middlewares to Redux? You can use applyMiddleware()
...
How to set initial state in Redux? 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 ) � Back to Top 187
...
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)
...
188
...
They are the only source of information for the store
...
For example, let’s take an action which represents adding a new todo item: 92
{ type: ADD_TODO, text: 'Add todo item' } � Back to Top
React Native � Back to Top 188
...
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
...
How to test React Native apps? React Native can be tested only in mobile simulators like iOS and Android
...
io) Where it syncs using QR code, your mobile and computer should be in same wireless network
...
How to do logging in React Native? You can use console
...
warn, etc
...
29 you can simply run the following to see logs in the console: $ react-native log-ios $ react-native log-android � Back to Top 191
...
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
...
What is reselect and how it works? Reselect is a selector library (for Redux) which uses memoization concept
...
Reselect keeps a copy of the last inputs/outputs of the last call, and recomputes the result only if one of the inputs changes
...
It’s memoization and cache are fully customizable
...
What is Flow? Flow is a static type checker designed to find type errors in JavaScript
...
For example, Flow helps you catch errors involving null, unlike most type systems
...
What is the difference between Flow and PropTypes? 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
...
It can’t check anything other than the types of the props being passed to a given component
...
� Back to Top 195
...
Install font-awesome: $ npm install --save font-awesome 2
...
js file: import 'font-awesome/css/font-awesome
...
css' 3
...
What is React Dev Tools? React Developer Tools let you inspect the component hierarchy, including component props and state
...
The official extensions available for different browsers or environments
...
Chrome extension 2
...
Standalone app (Safari, React Native, etc) � Back to Top 197
...
) then you must first open Chrome Extensions and check Allow access to file URLs
...
How to use Polymer in React? You need to follow below steps to use Polymer in React, 1
...
/bower_components/polymer/polymer
...
textContent = 'I am a calender' } }) 2
...
g
...
html of your React application:
3
...
Component { render() { return ( ) } } export default MyComponent � Back to Top 199
...
js? React has the following advantages over Vue
...
2
...
4
...
Easier to test
...
More information and solutions available
...
But they are helpful as base parameters
...
What is the difference between React and Angular? Let’s see the difference between React and Angular in a table format
...
e it has two-way data binding between children and parent and hence debugging is often difficult
Note: The above list of differences are purely opinionated and it vary based on the professional experience
...
� Back to Top 201
...
If the website is not using React or if React fails to communicate with DevTools then it won’t show up the tab
...
What are Styled Components? styled-components is a JavaScript library for styling React applications
...
97
� Back to Top 203
...
import React from 'react' import styled from 'styled-components' // Create a component that renders an
which is centered, red and sized at const Title = styled
...
5em; text-align: center; color: palevioletred; `
// Create a component that renders a with some padding and a papaya const Wrapper = styled
...
jsx harmony {'Lets start first styled component!'} � Back to Top 204
...
� Back to Top 205
...
1
...
i
...
You can just pass --typescript option as below
98
npx create-react-app my-app --typescript # or yarn create react-app my-app --typescript But for lower versions of react scripts, just supply --scripts-version option as react-scripts-ts while you create a new project
...
Now the project layout should look like the following: my-app/ ��
...
d
...
Does the statics object work with ES6 classes in React? No, statics only works with React
...
createClass({ statics: { someMethod: function() {
100
//
...
Component { static propTypes = { //
...
} } or writing them outside class as below, class Component extends React
...
} Component
...
} Component
...
} � Back to Top 210
...
The most common usage is with React and React Native, but there are bindings available for Angular, Angular 2, Vue, Mithril, and more
...
� Back to Top 211
...
You should be able to use it regardless of your JavaScript build process
...
� Back to Top 212
...
const InitializeFromStateForm = reduxForm({ form: 'initializeFromState', enableReinitialize : true })(UserEdit) If your initialValues prop gets updated, your form will update too
...
How React PropTypes allow different types for one prop? You can use oneOfType() method of PropTypes
...
propTypes = { size: PropTypes
...
string, PropTypes
...
Can I import an SVG file as react component? You can import SVG directly as component instead of loading it as a file
...
0
...
“‘jsx harmony import { ReactComponent as Logo } from ‘
...
svg’ const App = () => ( {/* Logo is an actual react component */} ) “‘ Note: Don’t forget about the curly braces in the import
...
102
Why are inline ref callbacks or functions not recommended? If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element
...
class UserForm extends Component { handleSubmit = () => { console
...
input
...
handleSubmit}> type='text' ref={(input) => this
...
One quick fix is to use the ES7 class property syntax to define the function class UserForm extends Component { handleSubmit = () => { console
...
input
...
input = input } render () { return (
)
103
} } **Note:** In React v16
...
What is render hijacking in react? The concept of render hijacking is the ability to control what a component will output from another component
...
By wrapping, you can inject additional props or make other changes, which can cause changing logic of rendering
...
� Back to Top 217
...
1
...
Inheritance Inversion (II)
...
Props Proxy In this approach, the render method of the HOC returns a React Element of the type of the WrappedComponent
...
function ppHOC(WrappedComponent) { return class PP extends React
...
this
...
It is called Inheritance Inversion because instead of the WrappedComponent extending some Enhancer class, it is passively
104
extended by the Enhancer
...
function iiHOC(WrappedComponent) { return class Enhancer extends WrappedComponent { render() { return super
...
How to pass numbers to React component? You should be passing the numbers via curly braces({}) where as strings in quotes
React
...
getElementById('container � Back to Top 219
...
e
...
Some users prefer to keep every single piece of data in Redux, to maintain a fully serializable and controlled version of their application at all times
...
Below are the thumb rules to determine what kind of data should be put into Redux 1
...
Do you need to be able to create further derived data based on this original data? 3
...
Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)? 5
...
e, use what’s in state if it’s already there instead of re-requesting it)? � Back to Top
105
220
...
The service worker is a web API that helps you cache your assets and other files so that when the user is offline or on a slow network, he/she can still see results on the screen, as such, it helps you build a better user experience, that’s what you should know about service worker for now
...
import import import import
React from 'react'; ReactDOM from 'react-dom'; App from '
...
/registerServiceWorker';
ReactDOM
...
getElementById('root')); registerServiceWorker(); � Back to Top 221
...
Now you can do the same with function components by wrapping them in React
...
const MyComponent = React
...
What is React lazy function? The React
...
It will automatically load the bundle containing the OtherComponent when the component gets rendered
...
); } Note: React
...
If you want to do code-splitting in a server rendered app, we still recommend React Loadable
...
How to prevent unnecessary updates using setState? You can compare the current value of the state with an existing state value and decide whether to rerender the page or not
...
For example, the user profile information is conditionally rendered as follows, getUserProfile = user const latestAddress this
...
address return null; } else { return { title: } }); };
=> { = user
...
How do you render Array, Strings and Numbers in React 16 Version? Arrays: Unlike older releases, you don’t need to make sure render method return a single element in React16
...
For example, let us take the below list of developers, const ReactJSDevs = () => { return [
John
, 107
Jackie
,
Jordan
]; } You can also merge this array of items in another array component
...
render() { return 'Welcome to ReactJS questions'; } // Number render() { return 2018; } � Back to Top 225
...
You can initialize the local state without using the constructor and declare class methods by using arrow functions without the extra need to bind them
...
setState(prevState => ({ value: prevState
...
setState(prevState => ({ value: prevState
...
state
...
handleIncrement}>+
...
What are hooks? Hooks is a new feature(React 16
...
Let’s see an example of useState hook: import { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return (
You clicked {count} times
setCount(count + 1)}> Click me
); } � Back to Top
109
227
...
Call Hooks only at the top level of your react functions
...
e, You shouldn’t call Hooks inside loops, conditions, or nested functions
...
2
...
i
...
� Back to Top 228
...
You can add this plugin to your project using the below command, javascript npm install eslint-plugin-react-hooks@next And apply the below config in your ESLint config file, javascript // Your ESLint configuration { "plugins": [ //
...
"react-hooks/rules-of-hooks": "error" } } Note: This plugin is intended to use in Create React App by default
...
What are the differences between Flux and Redux? Below are the major differences between Flux and Redux Flux
Redux
State is mutable The Store contains both state and change logic There are multiple stores exist All the stores are disconnected and flat It has a singleton dispatcher React components subscribe to the store
State is immutable The Store and change logic are separate There is only one store exist Single store with hierarchical reducers There is no concept of dispatcher Container components uses connect function
110
� Back to Top 230
...
In React Router v4(version 4), the API is completely about components
...
2
...
The router module will take care history by wrapping routes with component
...
The application size is reduced by adding only the specific router module(Web, core, or native) � Back to Top 231
...
The method receives two parameters, 1
...
info: - An object with a componentStack key contains the information about which component threw the error
...
In which scenarios error boundaries do not catch errors? Below are the cases in which error boundaries doesn’t work, 1
...
Asynchronous code using setTimeout or requestAnimationFrame callbacks 3
...
When errors thrown in the error boundary code itself � Back to Top 233
...
React doesn’t need error boundaries to recover from errors in event handlers
...
So if they throw, React still knows what to display on the screen
...
Component { constructor(props) { super(props); this
...
handleClick = this
...
bind(this); } handleClick() { try { // Do something that could throw } catch (error) { this
...
state
...
} return
...
� Back to Top 234
...
For example, the try catch block used for below imperative code
112
try { showButton(); } catch (error) { //
...
� Back to Top 235
...
The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it
...
� Back to Top 236
...
You can follow either of these approaches, 1
...
2
...
� Back to Top 237
...
113
For example, BuggyCounter component displays the component stack trace as below,
Figure 8: stacktrace � Back to Top 238
...
i
...
� Back to Top 239
...
React elements: Elements that instruct React to render a DOM node
...
2
...
Portals: Render children into a different DOM subtree
...
String and numbers: Render both Strings and Numbers as text nodes in the DOM 5
...
� Back to Top 240
...
To initialize local state by assigning object to this
...
For binding event handler methods to the instance For example, the below code covers both the above cases, constructor(props) { super(props); // Don't call this
...
state = { counter: 0 }; this
...
handleClick
...
Is it mandatory to define constructor for React component? No, it is not mandatory
...
e, If you don’t initialize state and you don’t bind methods, you don’t need to implement a constructor for your React component
...
What are default props? The defaultProps are defined as a property on the component class to set the default props for the class
...
For example, let us create color default prop for the button component, class MyButton extends React
...
} MyButton
...
color is not provided then it will set the default value to ‘red’
...
e, Whenever you try to access the color prop it uses default value render() { return ; // props
...
� Back to Top 243
...
� Back to Top 244
...
It receives the error that was thrown as a parameter and should return a value to update state
...
Component { constructor(props) { super(props); this
...
return { hasError: true }; } render() { if (this
...
hasError) { // You can render any custom fallback UI return
Something went wrong
...
props
...
What is the methods order when component re-rendered? An update can be caused by changes to props or state
...
116
1
...
3
...
5
...
What are the methods invoked during error handling? Below methods are called when there is an error during rendering, in a lifecycle method, or in the constructor of any child component
...
static getDerivedStateFromError() 2
...
What is the purpose of displayName class property? The displayName string is used in debugging messages
...
You might want to set it explicitly if you want to display a different name for debugging purposes or when you create a higher-order component
...
function withSubscription(WrappedComponent) { class WithSubscription extends React
...
*/ } WithSubscription
...
displayName || WrappedComponent
...
What is the browser support for react applications? React supports all popular browsers, including Internet Explorer 9 and above, although some polyfills are required for older browsers such as IE
117
9 and IE 10
...
� Back to Top 249
...
If no component was mounted in the container, calling this function does nothing
...
The method signature would be as follows, ReactDOM
...
What is code-splitting? Code-Splitting is a feature supported by bundlers like Webpack and Browserify which can create multiple bundles that can be dynamically loaded at runtime
...
For example, in the below code snippets, it will make moduleA
...
moduleA
...
js import React, { Component } from 'react'; class App extends Component { handleClick = () => { import('
...
then(({ moduleA }) => { // Use moduleA })
...
handleClick}>Load
); } } export default App; � Back to Top 251
...
2
...
4
...
Identifying components with unsafe lifecycle methods
...
Detecting unexpected side effects
...
Warning about deprecated findDOMNode usage
� Back to Top 252
...
Fragment> syntax may have keys
...
items
...
Fragment key={item
...
term}
{item
...
Fragment> ))}
119
); } Note: key is the only attribute that can be passed to Fragment
...
� Back to Top 253
...
Since React components often take both custom and DOM-related props, React uses the camelCase convention just like the DOM APIs
...
tabIndex DOM API // Just like node
...
readOnly DOM API These props work similarly to the corresponding HTML attributes, with the exception of the special cases
...
� Back to Top 254
...
Below are the few listed in an order, 1
...
render() { // A new version of EnhancedComponent is created on every render // EnhancedComponent1 !== EnhancedComponent2 const EnhancedComponent = enhance(MyComponent); // That causes the entire subtree to unmount/remount each time! return ; } The above code impacts on performance by remounting a component that causes the state of that component and all of its children to be lost
...
120
2
...
staticMethod = function() {/*
...
staticMethod === 'undefined' // true You can overcome this by copying the methods onto the container before returning it, function enhance(WrappedComponent) { class Enhance extends React
...
*/ } // Must know exactly which method(s) to copy :( Enhance
...
staticMethod; return Enhance; } 3
...
This is because ref is not really a prop similar to key
...
forwardRef API � Back to Top 255
...
forwardRef accepts a render function as parameter and DevTools uses this function to determine what to display for the ref forwarding component
...
forwardRef((props, ref) => { return
...
forwardRef( function myFunction(props, ref) { return
...
Component { //
...
props} forwardedRef={ref} />; } // Give this component a more helpful display name in DevTools
...
g
...
displayName || Component
...
displayName = `logProps(${name})`; return React
...
When component props defaults to true? If you pass no value for a prop, it defaults to true
...
For example, below expressions are equivalent, Note: It is not recommended to use this approach because it can be confused with the ES6 object shorthand (example, {name} which is short for {name: name}) � Back to Top 257
...
js is a popular and lightweight framework for static and server‑rendered applications built with React
...
Below are the major features provided by NextJS, 122
1
...
3
...
5
...
Server-rendered by default Automatic code splitting for faster page loads Simple client-side routing (page based) Webpack-based dev environment which supports (HMR) Able to implement with Express or any other Node
...
How do you pass an event handler to a component? You can pass event handlers and other functions as props to child components
...
handleClick}> � Back to Top 259
...
It is often the easiest way to pass parameters to callback functions
...
class Foo extends Component { handleClick() { console
...
handleClick()}>Click Me; } } Note: Using an arrow function in render method creates a new function each time the component renders, which may have performance implications � Back to Top 260
...
This can be achieved in the below possible ways,
123
1
...
For example, it can be used using _
...
Debouncing: Publish changes after a period of inactivity
...
debounce lodash function 3
...
For example, it can be used using raf-schd lodash function � Back to Top 261
...
Thus it ensures that you can never inject anything that’s not explicitly written in your application
...
For example, you can embed user input as below, const name = response
...
� Back to Top 262
...
For example, lets take a ticking clock example, where it updates the time by calling render method multiple times, function tick() { const element = (
Let us take a below capital function, function capital(amount, interest) { return amount + interest; } The above function is called “pure” because it does not attempt to change their inputs, and always return the same result for the same inputs
...
” � Back to Top 264
...
For example, let us take a facebook user with posts and comments details as state variables, constructor(props) { super(props); this
...
then(response => { this
...
posts }); }); fetchComments()
...
setState({ comments: response
...
setState({comments}) updates only comments variable without modifying or replacing posts variable
...
How do you pass arguments to an event handler? During iterations or loops, it is common to pass an extra parameter to an event handler
...
Let us take an example of user details updated in a grid, this
...
updateUser
...
You need to pass it explicitly for arrow functions and it will be passed automatically for bind method
...
How to prevent component from rendering? You can prevent component from rendering by returning null based on specific condition
...
function Greeting(props) { if (!props
...
name}
); }
126
class User extends React
...
state = {loggedIn: false, name: 'John'}; } render() { return (
//Prevent component render if it is not loggedIn
...
loggedIn} />
...
name}>
); } In the above example, the greeting component skips its rendering section by applying condition and returning null value
...
What are the conditions to safely use the index as a key? There are three conditions to make sure, it is safe use the index as a key
...
The list and items are static– they are not computed and do not change 2
...
The list is never reordered or filtered
...
Should keys be globally unique? The keys used within arrays should be unique among their siblings but they don’t need to be globally unique
...
e, You can use the same keys with two different arrays
...
pages
...
id}>
127
{page
...
pages
...
id}>
{page
...
content}
{page
...
What is the popular choice for form handling? Formik is a form library for react which provides solutions such as validation, keeping track of the visited fields, and handling form submission
...
Getting values in and out of form state 2
...
Handling form submission It is used to create a scalable, performant, form helper with a minimal API to solve annoying stuff
...
What are the advantages of formik over redux form library? Below are the main reasons to recommend formik over redux form library, 1
...
128
2
...
This way it increases input latency for large apps
...
Redux-Form is 22
...
7 kB � Back to Top 271
...
Both Props and composition give you all the flexibility you need to customize a component’s look and behavior explicitly and safely
...
Later components import it and use that function, object, or class, without extending it
...
Can I use web components in react application? Yes, you can use web components in a react application
...
For example, let us use Vaadin date picker web component as below, import React, { Component } from 'react'; import '
...
css'; import '@vaadin/vaadin-date-picker'; class App extends Component { render() { return (
); } } export default App; � Back to Top 273
...
Let’s take an example of addition, 1
...
/math'; console
...
Dynamic Import import("
...
then(math => { console
...
add(10, 20)); }); � Back to Top 274
...
lazy and Suspense is not yet available for server-side rendering
...
Lets take an example, import loadable from '@loadable/component' const OtherComponent = loadable(() => import('
...
What is suspense component? If the module containing the dynamic import is not yet loaded by the time parent component renders, you must show some fallback content
130
while you’re waiting for it to load using a loading indicator
...
For example, the below code uses suspense component, const OtherComponent = React
...
/OtherComponent')); function MyComponent() { return (
Loading
...
� Back to Top 276
...
The entire page is going to re-render at once so users are unlikely to interact with other elements in the page at the same time
...
Let us take an example of route based website using libraries like React Router with React
...
/routes/Home')); const About = lazy(() => import('
...
}>
131
); In the above code, the code splitting will happen at each route level
...
Give an example on How to use context? Context is designed to share data that can be considered global for a tree of React components
...
//Lets create a context with a default theme value "luna" const ThemeContext = React
...
Component { render() { return (
...
Provider> ); } } // A middle component where you don't need to pass theme prop anymore function Toolbar(props) { return (
); } // Lets read theme value in the button component to use class ThemedButton extends React
...
context} />; } } � Back to Top 278
...
This can be helpful for testing components in isolation without wrapping them
...
const MyContext = React
...
How do you use contextType? ContextType is used to consume the context object
...
contextType as property of class: The contextType property on a class can be assigned a Context object created by React
...
After that, you can consume the nearest current value of that Context type using this
...
Lets assign contextType property on MyClass as below, class MyClass extends React
...
context; /* perform a side-effect at mount using the value of MyContext */ } componentDidUpdate() { let value = this
...
*/ } componentWillUnmount() { let value = this
...
*/ } render() { let value = this
...
contextType = MyContext; 2
...
133
class MyClass extends React
...
context; /* render something based on the value */ } } � Back to Top 280
...
It requires a function as a child which receives current context value as argument and returns a react node
...
Lets take a simple example,
...
Consumer> � Back to Top 281
...
For example, the code below will re-render all consumers every time the Provider re-renders because a new object is always created for value
...
Component { render() { return (
); } } This can be solved by lifting up the value to parent state,
134
class App extends React
...
state = { value: {something: 'something'}, }; } render() { return (
...
value}>
); } } � Back to Top 282
...
It is handled differently by React just like key
...
In this case, you can use Forward Ref API
...
forwardRef API
...
Component { componentDidUpdate(prevProps) { console
...
log('new props:', this
...
rest} = this
...
rest} />; } } return React
...
props} forwardedRef={ref} />; }); } Let’s use this HOC to log all props that get passed to our “fancy button” component, class FancyButton extends React
...
} //
...
In this case, you can set focus to button element
...
/FancyButton'; const ref = React
...
current
...
Is ref argument available for all functions or class components? Regular function or class components don’t receive the ref argument, and ref is not available in props either
...
forwardRef call
...
Why do you need additional care for component libraries while using forward refs? When you start using forwardRef in a component library, you should treat it as a breaking change and release a new major version of your library
...
These changes can break apps and other libraries that depend on the old behavior
...
How to create react class components without ES6? If you don’t use ES6 then you may need to use the create-react-class module instead
...
Whereas for initial state, you have to provide a separate getInitialState method that returns the initial state
...
props
...
log(this
...
message); }, render: function() { return
Hello, {this
...
name}
; } }); Note: If you use createReactClass then auto binding is available for all methods
...
e, You don’t need to use
...
� Back to Top 286
...
Actually it is convenient when you don’t want to set up compilation in your build environment
...
createElement(component, props,
...
For example, let us take a greeting example with JSX, class Greeting extends React
...
props
...
render( , document
...
Component { render() { return React
...
props
...
render( React
...
getElementById('root') ); � Back to Top 287
...
The diffing algorithms is generating the minimum number of operations to transform one tree into another
...
In this case, displaying 1000 elements would require in the order of one billion comparisons
...
Instead, React implements a heuristic O(n) algorithm based on two assumptions: 1
...
2
...
� Back to Top 288
...
The behavior is different depending on the types of the root elements
...
Elements Of Different Types: Whenever the root elements have different types, React will tear down the old tree and build the new tree from scratch
...
2
...
Lets take an example with same DOM elements except className attribute,
3
...
React updates the props of the underlying component instance to match the new element, and calls componentWillReceiveProps() and componentWillUpdate() on the underlying instance
...
4
...
For example, when adding an element at the end of the children, converting between these two trees works well
...
Handling keys: React supports a key attribute
...
For example, adding a key can make the tree conversion efficient,
Duke
139
Villanova
Connecticut
Duke
Villanova
� Back to Top 289
...
Managing focus, text selection, or media playback
...
Triggering imperative animations
...
Integrating with third-party DOM libraries
...
Must prop be named as render for render props? Even though the pattern named render props, you don’t have to use a prop named render to use this pattern
...
e, Any prop that is a function that a component uses to know what to render is technically a “render prop”
...
x}, {mouse
...
Instead, you can keep it directly inside element, {mouse => (
The mouse position is {mouse
...
y}
)}
While using this above technique(without any name), explicitly state that children should be a function in your propTypes
...
propTypes = { children: PropTypes
...
isRequired };
140
� Back to Top 291
...
Because the shallow prop comparison will always return false for new props, and each render in this case will generate a new value for the render prop
...
� Back to Top 292
...
For example, if you would prefer to have a withMouse HOC instead of a component, you could easily create one using a regular with a render prop
...
Component { render() { return ( (
...
props} mouse={mouse} /> )}/> ); } } } This way render props gives the flexibility of using either pattern
...
What is windowing technique? Windowing is a technique that only renders a small subset of your rows at any given time, and can dramatically reduce the time it takes to re-render the components as well as the number of DOM nodes created
...
Both react-window and react-virtualized are popular windowing libraries
141
which provides several reusable components for displaying lists, grids, and tabular data
...
How do you print falsy values in JSX? The falsy values such as false, null, undefined, and true are valid children but they don’t render anything
...
Let’s take an example on how to convert to a string,
My JavaScript variable is {String(myVariable)}
...
What is the typical use case of portals? React portals are very useful when a parent component has overflow: hidden or has properties that affect the stacking context (e
...
z-index, position, opacity) and you need to visually “break out” of its container
...
� Back to Top 296
...
With an uncontrolled component, you might want React to specify the initial value, but leave subsequent updates uncontrolled
...
render() { return (
); } The same applies for select and textArea inputs
...
� Back to Top 297
...
It mainly uses Redux and redux-saga for state management and asynchronous side-effects, react-router for routing purpose, styled-components for styling react components, axios for invoking REST api, and other supported stack such as webpack, reselect, ESNext, Babel
...
com/react-boilerplate/react-boilerplate and start working on any new react project
...
What is the difference between Real DOM and Virtual DOM? Below are the main differences between Real DOM and Virtual DOM, Real DOM
Virtual DOM
Updates are slow DOM manipulation is very expensive
...
It causes too much of memory wastage Creates a new DOM if element updates
Updates are fast DOM manipulation is very easy You Can’t directly update HTML There is no memory wastage It updates the JSX if element update
� Back to Top 299
...
Using the Bootstrap CDN: This is the easiest way to add bootstrap
...
2
...
React Bootstrap Package: In this case, you can add Bootstrap to our React app is by using a package that has rebuilt Bootstrap components to work particularly as React components
...
react-bootstrap 2
...
Can you list down top websites or applications using react as front end framework? Below are the top 10 websites using React as their front-end framework, 1
...
� Back to Top 301
...
css file as usual and refer to them using className
...
But If you want to try a different approach(CSS-In-JS) then styled-components library is a good option
...
Do I need to rewrite all my class components with hooks? No
...
Because there are no plans to remove classes in ReactJS
...
How to fetch data with React Hooks? The effect hook called useEffect is used to fetch the data with axios from the API and to set the data in the local state of the component with the state hook’s update function
...
algolia
...
data); })() }, []); return (
{data
...
map(item => (
...
url}>{item
...
i
...
� Back to Top 304
...
Currently there are no Hook equivalents to the uncommon getSnapshotBeforeUpdate and componentDidCatch lifecycles yet
...
What is the stable release for hooks support? React includes a stable implementation of React Hooks in 16
...
2
...
4
...
Why do we use array destructuring (square brackets notation) in useState? When we declare a state variable with useState, it returns a pair — an array with two items
...
Using [0] and [1] to access them is a bit confusing because they have a specific meaning
...
For example, the array index access would look as follows: var userStateVariable = useState('userProfile'); // Returns an array pair var user = userStateVariable[0]; // Access first item var setUser = userStateVariable[1]; // Access second item Whereas with array destructuring the variables can be accessed as follows: const [user, setUser] = useState('userProfile'); � Back to Top
146
307
...
Below are some of them, 1
...
Community experiments with render prop APIs such as Reactions Component 3
...
4
...
5
...
� Back to Top 308
...
You will need to use a ref to interact with the DOM node directly if you want to access imperative API of a web component
...
� Back to Top 309
...
Getting values in and out of form state 2
...
Handling form submission � Back to Top 310
...
� Back to Top
147
311
...
You need a transpiler to convert your JSX to regular Javascript that browsers can understand
...
� Back to Top 312
...
� Back to Top 313
...
The react-scripts start command sets up the development environment and starts a server, as well as hot module reloading
...
What are the features of create react app? Below are the list of some of the features provided by create react app
...
React, JSX, ES6, Typescript and Flow syntax support
...
Autoprefixed CSS 3
...
A live development server 5
...
A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps 7
...
� Back to Top
148
315
...
It also helps search engines to crawl your pages easily for SEO purposes
...
� Back to Top 316
...
For reactJs application, you need to install below packages, bash npm install mobx --save npm install mobx-react --save � Back to Top 317
...
149
Should I learn ES6 before learning ReactJS? No, you don’t have to learn es2015/es6 to learn react
...
Let’s see some of the frequently used ES6 features, 1
...
props
...
props
...
props “‘ 2
...
props} /> “‘ 3
...
map(function (user) { return
{user
...
map(user =>
{user
...
What is Concurrent Rendering? The Concurrent rendering makes React apps to be more responsive by rendering component trees without blocking the main UI thread
...
i
...
You can enable this in two ways, // 1
...
unstable_ConcurrentMode>
...
Whole app using createRoot ReactDOM
...
render(); � Back to Top 320
...
Previously concurrent Mode being referred to as “Async Mode” by React team
...
So it avoids the confusion from other approaches to Async Rendering
...
Can I use javascript urls in react16
...
Because URLs starting with javascript: are dangerous by including unsanitized output in a tag like and create a security hole
...
website}>More details Remember that the future versions will throw an error for javascript URLs
...
What is the purpose of eslint plugin for hooks? The ESLint plugin enforces rules of Hooks to avoid bugs
...
In particular, the rule enforces that, 1
...
2
...
� Back to Top 323
...
When you tap it, it turns blue if it was previously grey, and grey if it was previously blue
...
likes() ) { if( hasBlue() ) { removeBlue(); addGrey(); } else { removeGrey(); addBlue(); } } Basically, you have to check what is currently on the screen and handle all the changes necessary to redraw it with the current state, including undoing the changes from the previous state
...
In contrast, the declarative approach would be: if( this
...
liked ) { return ; } else { return ; } Because the declarative approach separates concerns, this part of it only needs to handle how the UI should look in a sepecific state, and is therefore much simpler to understand
...
What are the benefits of using typescript with reactjs? Below are some of the benefits of using typescript with Reactjs, 1
...
3
...
It is possible to use latest JavaScript features Use of interfaces for complex type definitions IDEs such as VS Code was made for TypeScript Avoid bugs with the ease of readability and Validation
� Back to Top 325
...
js
...
152
App
...
/actions/auth'; store
...
js, wrap the AuthState in index
...
js can access the auth context
...
index
...
/App'; AuthState from '
...
render(
...
StrictMode>, document
...
js const authContext = useContext(AuthContext); const { loadUser } = authContext; useEffect(() => { loadUser(); },[]) loadUser const loadUser = async () => { const token = sessionStorage
...
data
...
error(err); } } � Back to Top 326
...
It is possible to use JSX without importing React packages 2
...
The future improvements provides the flexibility to reduce the number of concepts to learn React
...
How does new JSX transform different from old transform? The new JSX transform doesn’t require React to be in scope
...
e, You don’t need to import React package for simple scenarios
...
createElement('h1', null, 'Good morning!!'); } New Transform: The new JSX transform doesn’t require any React imports function App() { return
Good morning!!
; } Under the hood JSX transform compiles to below code import {jsx as _jsx} from 'react/jsx-runtime'; function App() { return _jsx('h1', { children: 'Good morning!!' }); } Note: You still need to import React to use Hooks
...
How do you get redux scaffolding using create-react-app? Redux team has provided official redux+js or redux+typescript templates for create-react-app project
...
What are React Server components? React Server Component is a way to write React component that gets rendered in the server-side with the purpose of improving React app performance
...
Note: React Server Components is still under development and not recommended for production yet
...
What is prop drilling? Prop Drilling is the process by which you pass data from one component of the React Component tree to another by going through other components that do not need the data but only help in passing it around
...
What is state mutation and how to prevent it? State mutation happens when you try to update the state of a component without actually using setState function
...
This is the main reason why it is advised to return new instances of state variables from the reducers by using Object
...
This can cause unknown issues in the UI as the value of the state variable got updated without telling React to check what all components were being affected from this update and it can cause UI bugs
...
component { constructor(props) { super(props); this
...
state; loading = (() => true)(); // Trying to perform an operation and directly saving in a state variable } “‘ How to prevent it: Make sure your state variables are immutable by either enforcing immutability by using plugins like Immutable
...
� Back to Top 332
...
useState causes components to re-render after state updates whereas useRef doesn’t cause a component to re-render when the value or state changes
...
current) property
...
useState allows us to update the state inside components
...
� Back to Top
Disclaimer The questions provided in this repository are the summary of frequently asked questions across numerous companies
...
The primary purpose is for you to get a sense of what some companies might ask — do not get discouraged if you don’t know the answer to all of them — that is ok! Good luck with your interview �
157
Title: Reactjs Interview Questions Description: React is a JavaScript-based UI development library. Facebook and an open-source developer community run it. Although React is a library rather than a language, it is widely used in web development. The library first appeared in May 2013 and is now one of the most commonly used frontend libraries for web development.in this notes i have done 300+ interview questions and answers so that is best for interview from my side