Top reactjs questions asked in interview
What is react Js?
React is an open-source front-end JavaScript library that is used for building user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps.
What are the main features of react?
The major features of React are:
- React uses JSX syntax, a syntax extension of javascript that allows developers to write HTML in their JS code.
- React uses Virtual DOM instead of RealDOM considering that RealDOM manipulations are expensive.
- Supports server-side rendering.
- React follows Unidirectional data flow or data binding.
- Uses reusable/composable UI components to develop the view.
- React can be used to build web as well as mobile application.
What is JSX?
JSX is a XML-like syntax extension to ECMAScript. Basically it just provides syntactic sugar for the React.createElement() function, giving us expressiveness of JavaScript along with HTML like template syntax.
The above react code can be written in plain javascript like below
What is the difference between Element and Component?
An Element is a plain object describing what you want to appear on the screen in terms of the DOM nodes or other components. Elements can contain other Elements in their props. Creating a React element is cheap. Once an element is created, it is never mutated.
The object representation of React Element would be as follows:
The above React.createElement() function returns an object:
And finally it renders to the DOM using ReactDOM.render():
Whereas a component can be declared in several different ways. It can be a class with a render() method or it can be defined as a function. In either case, it takes props as an input, and returns a JSX tree as the output:
Then JSX gets transpiled to a React.createElement() function tree:
How to create components in React?
There are two possible ways to create a component.
Function Components: This is the simplest way to create a component. Those are pure JavaScript functions that accept props object as the first parameter and return React elements:
Class Components: You can also use ES6 class to define a component. The above function component can be written as:
After the introduction of React Hooks in react, class based components are hardly used.
What are Pure Components in Reactjs?
In functional programming, A function is considerd to be pure when
- Its return value is only determined by its input values
- Its return value is always the same for the same input values
In react a component is said to be pure when it renders the same output for the same state and props. For class based component, React provides the PureComponent base class. Class components that extend the React.PureComponent class are treated as pure components.
Pure components have some performance improvements and render optimizations since React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state.
Are React functional components pure?
Functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since by definition, they are not classes, so they are not pure component.
If you want React to treat a functional component as a pure component, you’ll have to convert the functional component to a class component that extends React.PureComponent.
With React.memo(), you can create memoized functional components that bail out of rendering on unnecessary updates using shallow comparison of props.
Using the React.memo() API, the previous functional component can be wrapped as follows:
For one, React.memo() is a higher-order component. It takes a React component as its first argument and returns a special type of React component that allows the renderer to render the component while memoizing the output. Therefore, if the component’s props are shallowly equal, the React.memo() component will bail out the updates.
React.memo() works with all React components. The first argument passed to React.memo() can be any type of React component. However, for class components, you should use React.PureComponent instead of using React.memo(). React.memo() also works with components rendered from the server using ReactDOMServer.
What is state in React?
State of a component is an object that holds some information that may change over the lifetime of the component. We should always try to make our state as simple as possible and minimize the number of stateful components.
Let's create a user component with message state,
What are props in React?
Props are inputs to components. 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. They are data passed down from a parent component to a child component.
The primary purpose of props in React is to provide following component functionality:
- Pass custom data to your component.
- Trigger state changes.
- Use via this.props.reactProp inside component's render() method.
For example, let us create an element with reactProp property:
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.
Example: Props in Class Based Component
Example: Props in Functional Component
What is the difference between state and props?
Both props and state are plain JavaScript objects. While both of them hold information that influences the output of render, they are different in their functionality with respect to component.
Example of State:
Props get passed to the component similar to function parameters whereas state is managed within the component similar to variables declared within a function.
Example of props:
What is the use of key prop in reactjs?
A key is a special string attribute you should include when creating arrays of elements. Key prop helps React identify which items have changed, are added, or are removed.
Keys should be unique among its siblings. Most often we use ID from our data as key:
When you don't have stable IDs for rendered items, you may use the item index as a key as a last resort:
Note:
- Using indexes for keys is not recommended if the order of items may change. 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 React Hooks?
React Hooks are the built-in functions that permit developers for using the state and lifecycle methods within React components
Each lifecycle of a component is having 3 phases which include mount, unmount, and update. Along with that, components have properties and states. Hooks will allow using these methods by developers for improving the reuse of code with higher flexibility navigating the component tree.
Using Hook, all features of React can be used without writing class components. For example, before React version 16.8, it required a class component for managing the state of a component. But now using the useState hook, we can keep the state in a functional component.
- useState: It declares a state variable that you can update directly.
- useReducer: It declares a state variable with the update logic inside a reducer function.
- useContext: It reads and subscribes to a context.
- useRef declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node.
- useImperativeHandle lets you customize the ref exposed by your component. This is rarely used.
- useEffect connects a component to an external system.
- useMemo lets you cache the result of an expensive calculation.
- useCallback lets you cache a function definition before passing it down to an optimized component.
What is the use of React state Hooks?
React State lets a component remember information so that you can use it latter. In below example, we are defining a react state using useState and holding a initial value 0.
useState returns an array containing two value. The first one is current state and second one is a function which lets you change the state.
The set function set the new state and whenever a state is updated , component gets re-renderd.
set function can directly set a new state to new value
What is the use of useEffect Hooks in reactjs?
useEffect lets you invokes side effects from within functional components.
what is side effects?
A side effect is anything that affects something outside the scope of the function being executed. These can be a network request, which has your code communicating with a third party api, timer function like setTimeout.
useEffect is the hooks that lets you decouple the logic of rendering from side effects. Below code show data fetching side effects from an api. useEffect() starts a fetch request by calling fetchPosts() async function after the initial rendering. When the request completes, setPosts(posts) updates the posts state with the just fetched posts list.
useEffect needs two arguments
- A setup function which perform the side efects logic. It should return a cleanup function.
- A list of dependencies including every value from your component used inside of those functions. React calls your setup and cleanup functions whenever it’s necessary, which may happen multiple times:
Setup code runs when component is added to the page (mounts). After every re-render of component where the dependencies have changed:
- First, cleanup code runs with the old props and state.
- Then, setup code runs with the new props and state.
- cleanup code runs one final time after your component is removed from the page (unmounts).
What is the use of useContext Hooks in reactjs?
Context provides a way to pass data through the component tree without having to pass props through props drilling at every level.
useContext reads and subscribes to a context.
What is the use of useRef Hooks in reactjs?
Refs let a component hold some information that isn’t used for rendering, like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an “escape hatch” from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
useRef declares a ref. You can hold any value in it, but most often it’s used to hold a DOM node. useImperativeHandle lets you customize the ref exposed by your component. This is rarely used.
Parameters initialValue: The value you want the ref object’s current property to be initially. It can be a value of any type. This argument is ignored after the initial render. Returns useRef returns an object with a single property:
current: Initially, it’s set to the initialValue you have passed. You can later set it to something else. If you pass the ref object to React as a ref attribute to a JSX node, React will set its current property. On the next renders, useRef will return the same object.
What is the use of useMemo Hooks in reactjs?
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
useMemo takes two parameters, the first one is the function calculating the value that you want to cache and second one is dependencies.
-
calculateValue: The function calculating the value that you want to cache. It should be pure, should take no arguments, and should return a value of any type. React will call your function during the initial render. On subsequent renders, React will return the same value again if the dependencies have not changed since the last render. Otherwise, it will call calculateValue, return its result, and store it in case it can be reused later.
-
dependencies: The list of all reactive values referenced inside of the calculateValue code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison algorithm.
On the initial render, useMemo returns the result of calling calculateValue with no arguments.During subsequent renders, it will either return an already stored value from the last render (if the dependencies haven’t changed), or call calculateValue again, and return the result that calculateValue has returned.
Caveats
- useMemo is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
- In Strict Mode, React will call your calculation function twice in order to help you find accidental impurities. This is development-only behavior and does not affect production. If your calculation function is pure (as it should be), this should not affect the logic of your component. The result from one of the calls will be ignored.
- React will not throw away the cached value unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component. Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on useMemo solely as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.
Usage
By default, React will re-run the entire body of your component every time that it re-renders. For example, if this TodoList updates its state or receives new props from its parent, the filterTodos function will re-run:
What is the use of useCallback Hooks in reactjs?
useCallback is a React Hook that lets you cache a function definition between re-renders.
usecallback takes two parameters, the first one is function which you wants to cache and second one is dependencies.
-
fn: The function value that you want to cache. It can take any arguments and return any values. React will return (not call!) your function back to you during the initial render. On subsequent renders, React will give you the same function again if the dependencies have not changed since the last render. Otherwise, it will give you the function that you have passed during the current render, and store it in case it can be reused later. React will not call your function. The function is returned to you so you can decide when and whether to call it.
-
dependencies: The list of all reactive values referenced inside of the fn code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is configured for React, it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like [dep1, dep2, dep3]. React will compare each dependency with its previous value using the Object.is comparison algorithm.
useCallback returns the fn function you have passed.During subsequent renders, it will either return an already stored function from the last render (if the dependencies haven’t changed), or return the fn function you have passed during this render.
Caveats
-
useCallback is a Hook, so you can only call it at the top level of your component or your own Hooks. You can’t call it inside loops or conditions. If you need that, extract a new component and move the state into it.
-
React will not throw away the cached function unless there is a specific reason to do that. For example, in development, React throws away the cache when you edit the file of your component.
-
Both in development and in production, React will throw away the cache if your component suspends during the initial mount. In the future, React may add more features that take advantage of throwing away the cache—for example, if React adds built-in support for virtualized lists in the future, it would make sense to throw away the cache for items that scroll out of the virtualized table viewport. This should match your expectations if you rely on useCallback as a performance optimization. Otherwise, a state variable or a ref may be more appropriate.
Usage
Say you’re passing a handleSubmit function down from the ProductPage to the ShippingForm component:
In this example, the ShippingForm component is artificially slowed down so that you can see what happens when a React component you’re rendering is genuinely slow. Try incrementing the counter and toggling the theme.
Incrementing the counter feels slow because it forces the slowed down ShippingForm to re-render. That’s expected because the counter has changed, and so you need to reflect the user’s new choice on the screen.
Next, try toggling the theme. Thanks to useCallback together with memo, it’s fast despite the artificial slowdown! ShippingForm skipped re-rendering because the handleSubmit function has not changed. The handleSubmit function has not changed because both productId and referral (your useCallback dependencies) haven’t changed since last render.
How to make custom Hooks in reactjs?
React comes with several built-in Hooks like useState, useContext, and useEffect. Sometimes, you’ll wish that there was a Hook for some more specific purpose: for example, to fetch data, to keep track of whether the user is online, or to connect to a chat room. You might not find these Hooks in React, but you can create your own Hooks for your application’s needs.
What is Higher Order Components?
Higher-Order Component(HOC) is a function that takes in a component and returns a new component.
When do we need a Higher Order Component?
While developing React applications, we might develop components that are quite similar to each other with minute differences. In most cases, developing similar components might not be an issue but, while developing larger applications we need to keep our code DRY, therefore, we want an abstraction that allows us to define this logic in a single place and share it across components. HOC allows us to create that abstraction.
Example of a HOC: