React Js Interview Questions Ch. 2
Is it possible to use React without rendering HTML?
It is possible with latest version (>=16.2). Below are the possible options: Returning undefined won't work.
What is the benefit of styles modules?
It is recommended to avoid hard coding style values in components. Any values that are likely to be used across different UI components should be extracted into their own modules. For example, these styles could be extracted into a separate component:
Should I keep all component's state in Redux store?
Keep your data in the Redux store, and the UI related state internally in the component.
What are the popular packages for animation?
React Transition Group and React Motion are popular animation packages in React ecosystem.
Why is a component constructor called only once?
React's reconciliation algorithm assumes that without any information to the contrary, if a custom component appears in the same place on subsequent renders, it's the same component as before, so reuses the previous instance rather than creating a new one.
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. Redux Form can be used with raw HTML5 inputs, but it also works very well with common UI frameworks like Material UI, React Widgets and React Bootstrap. Some of the main features of Redux Form are: Field values persistence via Redux store. Validation (sync/async) and submission. Formatting, parsing and normalization of field values.
What is Redux?
Redux is a predictable state container for JavaScript apps based on the Flux design pattern. Redux can be used together with React, or with any other view library. It is tiny (about 2kB) and has no dependencies.
What is Shallow Renderer in React testing?
Shallow rendering is useful for writing unit test cases in React. It lets you render a component one level deep and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. For example, if you have the following component:
What is the main purpose of constructor?
The constructor is mainly used for two purposes, To initialize local state by assigning object to this.state For binding event handler methods to the instance For example, the below code covers both the above cases,
What are the rules needs to follow for hooks?
You need to follow two rules in order to use hooks, Call Hooks only at the top level of your react functions. i.e, You shouldn't call Hooks inside loops, conditions, or nested functions. This will ensure that Hooks are called in the same order each time a component renders and it preserves the state of Hooks between multiple useState and useEffect calls. Call Hooks from React Functions only. i.e, You shouldn't call Hooks from regular JavaScript functions.
How to use connect() from React Redux?
You need to follow two steps to use your store in your container: Use mapStateToProps(): It maps the state variables from your store to the props that you specify. Connect the above props to your container: The object returned by the mapStateToProps function is connected to the container. You can import connect() from react-redux.
How to update a component every second?
You need to use setInterval() to trigger the change, but you also need to clear the timer when the component unmounts to prevent errors and memory leaks.
Why do not you need error boundaries for event handlers?
Error boundaries do not catch errors inside event handlers. Event handlers don't happened or invoked during rendering time unlike render method or lifecycle methods. So React knows how to recover these kind of errors in event handlers. If still you need to catch an error inside event handler, use the regular JavaScript try / catch statement as below
What is Flow?
Flow is a static type checker designed to find type errors in JavaScript. Flow types can express much more fine-grained distinctions than traditional type systems. For example, Flow helps you catch errors involving null, unlike most type systems.
What is the use of the ownProps parameter in mapStateToProps() and mapDispatchToProps()?
If the ownProps parameter is specified, React Redux will pass the props that were passed to the component into your connect functions. So, if you use a connected component: The ownProps inside your mapStateToProps() and mapDispatchToProps() functions will be an object:
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. React Native ships with Babel and a set of transforms.
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.
What are the different ways to write mapDispatchToProps()?
There are a few ways of binding action creators to dispatch() in mapDispatchToProps().
How to define constants in React?
You can use ES7 static field to define constant. Static fields are part of the Class Fields stage 3 proposal.
How to import and export components using React and ES6?
You should use default for exporting the components With the export specifier, the MyProfile is going to be the member and exported to this module and the same can be imported without mentioning the name in other components.
How to implement default or NotFound page?
A <Switch> renders the first child <Route> that matches. A <Route> with no path always matches. So you just need to simply drop path attribute as below
What is a consumer?
A Consumer is a React component that subscribes to context changes. It requires a function as a child which receives current context value as argument and returns a react node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree.
What is the purpose of push() and replace() methods of history?
A history instance has two methods for navigation purpose. push() replace() If you think of the history as an array of visited locations, push() will add a new location to the array and replace() will replace the current location in the array with the new one.
What is an action in Redux?
Actions are plain JavaScript objects or payloads of information that send data from your application to your store. They are the only source of information for the store. Actions must have a type property that indicates the type of action being performed. For example, let's take an action which represents adding a new todo item:
How to add Google Analytics for React Router?
Add a listener on the history object to record each page view:
What is the methods order when component re-rendered?
An update can be caused by changes to props or state. The below methods are called in the following order when a component is being re-rendered. static getDerivedStateFromProps() shouldComponentUpdate() render() getSnapshotBeforeUpdate() componentDidUpdate()
In which scenarios error boundaries do not catch errors?
Below are the cases in which error boundaries doesn't work, Inside Event handlers Asynchronous code using setTimeout or requestAnimationFrame callbacks During Server side rendering When errors thrown in the error boundary code itself
What are the possible return types of render method?
Below are the list of following types used and return from render method, React elements: Elements that instruct React to render a DOM node. It includes html elements such as <div/> and user defined elements. Arrays and fragments: Return multiple elements to render as Arrays and Fragments to wrap multiple elements Portals: Render children into a different DOM subtree. String and numbers: Render both Strings and Numbers as text nodes in the DOM Booleans or null: Doesn't render anything but these types are used to conditionally render content.
How to get history on React Router v4?
Below are the list of steps to get history object on React Router v4, Create a module that exports a history object and import this module across the project. For example, create history.js file: You should use the <Router> component instead of built-in routers. Imported the above history.js inside index.js file: You can also use push method of history object similar to built-in history object:
What are the benefits of React Router V4?
Below are the main benefits of React Router V4 module, In React Router v4(version 4), the API is completely about components. A router can be visualized as a single component(<BrowserRouter>) which wraps specific child router components(<Route>). You don't need to manually set history. The router module will take care history by wrapping routes with <BrowserRouter> component. The application size is reduced by adding only the specific router module(Web, core, or native)
What are the possible ways of updating objects in state?
Calling setState() with an object to merge with state: Calling setState() with a function:
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. The react project supports code splitting via dynamic import() feature. For example, in the below code snippets, it will make moduleA.js and all its unique dependencies as a separate chunk that only loads after the user clicks the 'Load' button. moduleA.js
What is the difference between component and container in React Redux?
Component is a class or function component that describes the presentational part of your application. Container is an informal term for a component that is connected to a Redux store. Containers subscribe to Redux state updates and dispatch actions, and they usually don't render DOM elements; they delegate rendering to presentational child components.
What is the purpose of the constants in Redux?
Constants allows you to easily find all usages of that specific functionality across the project when you use an IDE. It also prevents you from introducing silly bugs caused by typos - in which case, you will get a ReferenceError immediately. Normally we will save them in a single file (constants.js or actionTypes.js).
Can I dispatch an action in reducer?
Dispatching an action within a reducer is an anti-pattern. Your reducer should be without side effects, simply digesting the action payload and returning a new state object. Adding listeners and dispatching actions within the reducer can lead to chained actions and other side effects.
What are the popular React-specific linters?
ESLint is a popular JavaScript linter. There are plugins available that analyse specific code styles. One of the most common for React is an npm package called eslint-plugin-react. By default, it will check a number of best practices, with rules checking things from keys in iterators to a complete set of prop types. Another popular plugin is eslint-plugin-jsx-a11y, which will help fix common issues with accessibility. As JSX offers slightly different syntax to regular HTML, issues with alt text and tabindex, for example, will not be picked up by regular plugins.
What is flux?
Flux is an application design paradigm used as a replacement for the more traditional MVC pattern. It is not a framework or a library but a new kind of architecture that complements React and the concept of Unidirectional Data Flow. Facebook uses this pattern internally when working with React. The workflow between dispatcher, stores and views components with distinct inputs and outputs as follows:
What are hooks?
Hooks is a new feature(React 16.8) that lets you use state and other React features without writing a class.
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. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. But our expectation is for the ref callback to get called once, when the component mounts. One quick fix is to use the ES7 class property syntax to define the function
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. For default props, you need to define getDefaultProps() as a function on the passed object. Whereas for initial state, you have to provide a separate getInitialState method that returns the initial state.
How to prevent a function from being called multiple times?
If you use an event handler such as onClick or onScroll and want to prevent the callback from being fired too quickly, then you can limit the rate at which callback is executed. This can be achieved in the below possible ways, Throttling: Changes based on a time based frequency. For example, it can be used using _.throttle lodash function Debouncing: Publish changes after a period of inactivity. For example, it can be used using _.debounce lodash function RequestAnimationFrame throttling: Changes based on requestAnimationFrame. For example, it can be used using raf-schd lodash function
What is the behavior of uncaught errors in react 16?
In React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree. The reason behind this decision is that it is worse to leave corrupted UI in place than to completely remove it. For example, it is worse for a payments app to display a wrong amount than to render nothing.
What are the downsides of Redux compared to Flux?
Instead of saying downsides we can say that there are few compromises of using Redux over Flux. Those are as follows: You will need to learn to avoid mutations: Flux is un-opinionated about mutating data, but Redux doesn't like mutations and many packages complementary to Redux assume you never mutate the state. You can enforce this with dev-only packages like redux-immutable-state-invariant, Immutable.js, or instructing your team to write non-mutating code. You're going to have to carefully pick your packages: While Flux explicitly doesn't try to solve problems such as undo/redo, persistence, or forms, Redux has extension points such as middleware and store enhancers, and it has spawned a rich ecosystem. There is no nice Flow integration yet: Flux currently lets you do very impressive static type checks which Redux doesn't support yet.
Do I need to keep all my state into Redux? Should I ever use react internal state?
It is up to developer decision. i.e, It is developer job to determine what kinds of state make up your application, and where each piece of state should live. 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. Others prefer to keep non-critical or UI state, such as "is this dropdown currently open", inside a component's internal state. Below are the thumb rules to determine what kind of data should be put into Redux Do other parts of the application care about this data? Do you need to be able to create further derived data based on this original data? Is the same data being used to drive multiple components? Is there value to you in being able to restore this state to a given point in time (ie, time travel debugging)? Do you want to cache the data (i.e, use what's in state if it's already there instead of re-requesting it)?
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. It's often used for testing components.
How to structure Redux top level directories?
Most of the applications has several top-level directories as below: 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. This structure works well for small and medium size apps.
What is NextJS and major features of it?
Next.js is a popular and lightweight framework for static and server‑rendered applications built with React. It also provides styling and routing solutions. Below are the major features provided by NextJS, 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.js HTTP server Customizable with your own Babel and Webpack configurations
What is React Dev Tools?
React Developer Tools let you inspect the component hierarchy, including component props and state. It exists both as a browser extension (for Chrome and Firefox), and as a standalone app (works with other environments including Safari, IE, and React Native). The official extensions available for different browsers or environments. Chrome extension Firefox extension Standalone app (Safari, React Native, etc)
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.history with its browser and hash histories. It also provides memory history which is useful for environments that don't have global history, such as mobile app development (React Native) and unit testing with Node.
What are the <Router> components of React Router v4?
React Router v4 provides below 3 <Router> components: <BrowserRouter> <HashRouter> <MemoryRouter> The above components will create browser, hash, and memory history instances. React Router v4 makes the properties and methods of the history instance associated with your router available through the context in the router object.
How do you apply vendor prefixes to inline styles in React?
React does not apply vendor prefixes automatically. You need to add vendor prefixes manually.
What is the difference between React Native and React?
React is a JavaScript library, supporting both front end web and being run on the server, for building user interfaces and web applications. React Native is a mobile framework that compiles to native app components, allowing you to build native mobile applications (iOS, Android, and Windows) in JavaScript that allows you to use React to build your components, and implements React under the hood.
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.
Why are Redux state functions called reducers?
Reducers always return the accumulation of the state (based on all previous and current actions). Therefore, they act as a reducer of state. Each time a Redux reducer is called, the state and action are passed as parameters. This state is then reduced (or accumulated) based on the action, and then the next state is returned. You could reduce a collection of actions and an initial state (of the store) on which to perform these actions to get the resulting final state.
What is Redux DevTools?
Redux DevTools is a live-editing time travel environment for Redux with hot reloading, action replay, and customizable UI. If you don't want to bother with installing Redux DevTools and integrating it into your project, consider using Redux DevTools Extension for Chrome and Firefox. 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 re-evaluated. 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 is Redux Thunk?
Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch() and getState() as parameters.
What are the core principles of Redux?
Redux follows three fundamental principles: Single source of truth: The state of your whole application is stored in an object tree within a single store. The single state tree makes it easier to keep track of changes over time and debug or inspect the application. State is read-only: The only way to change the state is to emit an action, an object describing what happened. This ensures that neither the views nor the network callbacks will ever write directly to the state. Changes are made with pure functions: To specify how the state tree is transformed by actions, you write reducers. Reducers are just pure functions that take the previous state and an action as parameters, and return the next state.
What are render props?
Render Props is a simple technique for sharing code between components using a prop whose value is a function. The below component uses render prop which returns a React element. Libraries such as React Router and DownShift are using this pattern.
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. For example, to get user details from the state: const getUserData = state => state.user.data These selectors have two main benefits, The selector can compute derived data, allowing Redux to store the minimal possible state The selector is not recomputed unless one of its arguments changes
Why you can't update props in React?
The React philosophy is that props should be immutable and top-down. This means that a parent can send any prop values to a child, but the child can't modify received props.
How 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. So the decision has been given to users to choose the implementation they like. The recommended approach is to use query strings library. You can also use URLSearchParams if you want something native: You should use a polyfill for IE11.
What is the proper way to access Redux store?
The best way to access your store in a component is to use the connect() function, that creates a new component that wraps around your existing one. This pattern is called Higher-Order Components, and is generally the preferred way of extending a component's functionality in React. This allows you to map state and action creators to your component, and have them passed in automatically as your store updates. Due to it having quite a few performance optimizations and generally being less likely to cause bugs, the Redux developers almost always recommend using connect() over accessing the store directly (using context API).
What is the recommended approach of removing an array element in React state?
The better approach is to use Array.prototype.filter() method. For example, let's create a removeItem() method for updating the state.
Can you describe about componentDidCatch lifecycle method signature?
The componentDidCatch lifecycle method is invoked after an error has been thrown by a descendant component. The method receives two parameters, error: - The error object which was thrown info: - An object with a componentStack key contains the information about which component threw the error. componentDidCatch(error, info)
How to listen to state changes?
The componentDidUpdate lifecycle method will be called when state changes. You can compare provided state and props values with current state and props to determine if something meaningful changed. Note: The previous releases of ReactJS also uses componentWillUpdate(object nextProps, object nextState) for state changes. It has been deprecated in latest releases.
What are default props?
The defaultProps are defined as a property on the component class to set the default props for the class. This is used for undefined props, but not for null props.
How to perform automatic redirect after login?
The react-router package provides <Redirect> component in React Router. Rendering a <Redirect> will navigate to a new location. Like server-side redirects, the new location will override the current location in the history stack.
What is the benefit of strict mode?
The will be helpful in the below cases Identifying components with unsafe lifecycle methods. Warning about legacy string ref API usage. Detecting unexpected side effects. Detecting legacy context API. Warning about deprecated findDOMNode usage
What are the approaches to include polyfills in your create-react-app
There are approaches to include polyfills in create-react-app, Manual import from core-js: Create a file called (something like) polyfills.js and import it into root index.js file. Run npm install core-js or yarn add core-js and import your specific required features. Using Polyfill service: Use the polyfill.io CDN to retrieve custom, browser-specific polyfills by adding this line to index.html: In the above script we had to explicitly request the Array.prototype.includes feature as it is not included in the default feature set.
What are the advantages of Jest over Jasmine?
There are couple of advantages compared to Jasmine: Automatically finds tests to execute in your source code. Automatically mocks dependencies when running your tests. Allows you to test asynchronous code synchronously. Runs your tests with a fake DOM implementation (via jsdom) so that your tests can be run on the command line. Runs tests in parallel processes so that they finish sooner.
How do you programmatically navigate using React Router v4?
There are three different ways to achieve programmatic routing/navigation within components. Using the withRouter() higher-order function: The withRouter() higher-order function will inject the history object as a prop of the component. This object provides push() and replace() methods to avoid the usage of context. Using <Route> component and render props pattern: The <Route> component passes the same props as withRouter(), so you will be able to access the history methods through the history prop. Using context: This option is not recommended and treated as unstable API.
What are the common folder structures for React?
There are two common practices for React project file structure. Grouping by features or routes: One common way to structure projects is locate CSS, JS, and tests together, grouped by feature or route. Grouping by file type: Another popular way to structure projects is to group similar files together.
What is the purpose of getDerivedStateFromError?
This lifecycle method is invoked after an error has been thrown by a descendant component. It receives the error that was thrown as a parameter and should return a value to update state.
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. This package makes it easy to grab a snapshot of the platform view hierarchy (similar to a DOM tree) rendered by a ReactDOM or React Native without using a browser or jsdom.
What is the difference between try catch block and error boundaries?
Try catch block works with imperative code whereas error boundaries are meant for declarative code to render on the screen. Whereas error boundaries wrap declarative code as below, So if an error occurs in a componentDidUpdate method caused by a setState somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
How to pretty print JSON with React?
We can use <pre> tag so that the formatting of the JSON.stringify() is retained:
What is the difference between setState() and replaceState() methods?
When you use setState() the current and previous states are merged. replaceState() throws out the current state, and replaces it with only what you provide. Usually setState() is used unless you really need to remove all previous keys for some reason. You can also set state to false/null in setState() instead of using replaceState().
How to pass params to history.push method in React Router v4?
While navigating you can pass props to the history object: The search property is used to pass query params in push() method.
Is it possible to use react without JSX?
Yes, JSX is not mandatory for using React. Actually it is convenient when you don't want to set up compilation in your build environment. Each JSX element is just syntactic sugar for calling React.createElement(component, props, ...children).
How to prevent unnecessary updates using setState?
You can compare current value of the state with an existing state value and decide whether to rerender the page or not. If the values are same then you need to return null to stop re-rendering otherwise return the latest state value.
How to dispatch an action on load?
You can dispatch an action in componentDidMount() method and in render() method you can verify the data.
How to focus an input element on page load?
You can do it by creating ref for input element and using it in componentDidMount():
How to prevent component from rendering?
You can prevent component from rendering by returning null based on specific condition. This way it can conditionally render component.
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. You should fetch data in the componentDidMount() lifecycle method. This is so you can use setState() to update your component when the data is retrieved. For example, the employees list fetched from API and set local state:
What is the difference between React context and React Redux?
You can use Context in your application directly and is going to be great for passing down data to deeply nested components which what it was designed for. Whereas Redux is much more powerful and provides a large number of features that the Context API doesn't provide. Also, React Redux uses context internally but it doesn't expose this fact in the public API.
How can we find the version of React at runtime in the browser?
You can use React.version to get the version.
How to add multiple middlewares to Redux?
You can use applyMiddleware(). For example, you can add redux-thunk and logger passing them as arguments to applyMiddleware():
How to make AJAX request in Redux?
You can use redux-thunk middleware which allows you to define async actions. Let's take an example of fetching specific account as an AJAX call using fetch API:
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.click method. This can be done in two steps: Create ref in render method: Apply click event in your event handler:
Why you get "Router may have only one child element" warning?
You have to wrap your Route's in a <Switch> block because <Switch> is unique in that it renders a route exclusively. At first you need to add Switch to your imports:
How to access Redux store outside a component?
You just need to export the store from the module where it created with createStore(). Also, it shouldn't pollute the global window object.
How to use https instead of http in create-react-app?
You just need to use HTTPS=true configuration. You can edit your package.json scripts section: or just run set HTTPS=true && npm start
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(). For example, let us take rootReducer() to return the initial state after USER_LOGOUT action. As we know, reducers are supposed to return the initial state when they are called with undefined as the first argument, no matter the action. In case of using redux-persist, you may also need to clean your storage. redux-persist keeps a copy of your state in a storage engine. First, you need to import the appropriate storage engine and then, to parse the state before setting it to undefined and clean each storage state key.
What is the difference between mapStateToProps() and mapDispatchToProps()?
mapStateToProps() is a utility which helps your component get updated state (which is updated by some other components): mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state): Recommend always using the "object shorthand" form for the mapDispatchToProps Redux wrap it in another function that looks like (...args) => dispatch(onTodoClick(...args)), and pass that wrapper function as a prop to your component.
What are Styled Components?
styled-components is a JavaScript library for styling React applications. It removes the mapping between styles and components, and lets you write actual CSS augmented with JavaScript.
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() componentDidCatch()
How to avoid using relative path imports in create-react-app?
Create a file called .env in the project root and write the import path: After that restart the development server. Now you should be able to import anything inside src/app without relative paths.