react js

hooks react interview questions, react hooks interview questions, interview questions on react hooks, react questions on hooks, react interview question and answer, top react interview question, interview question react, interview question react js

💡 What is a Hook in React?

Hooks are a new addition to React 16.8. Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes. React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components.

💡 Explain useState hook?

We call it inside a function component to add some local state to it. React will preserve this state between re-renders.
useState returns a pair: the current state value and a function that lets you update it.

💡 Explain useEffect?

The Effect Hook, useEffect, adds the ability to perform side effects from a function component. It serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes.
Effects are declared inside the component so they have access to its props and state.
By default, React runs the effects after every render — including the first render.

Effect cleanup function – If the effect does anything that needs to be cleaned up to prevent memory leaks, then the effect returns a cleanup function. The Effect Hook will call this cleanup function before calling the effect again as well as when the component is being unmounted from the DOM.

Dependency array – The dependency array is used to tell the useEffect() method when to call our effect. By default, with no dependency array provided, our effect is called after every render. An empty dependency array signals that our effect never needs to be re-run. A non-empty dependency array signals to the Effect Hook that it only needs to call our effect again when the value of one of the listed dependencies has changed.

// Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  // Empty dependency array
  useEffect(() => {
 alert('called after first render');
}, []);

// Non empty dependencies array
useEffect(() => {
 alert('called when value of `endpoint` or `id` changes');
}, [endpoint, id]);

// Clean up
useEffect(() => {
  document.addEventListener('keydown', handleKeydown);
  return () => {
	// clean up code like unsubsribe or remove listeners or clear values

💡 Why the effect cleanup phase happens after every re-render, and not just once during unmounting?

According to React’s official documentation, “React performs the cleanup when the component unmounts. However, effects run for every render and not just once. This is why React also cleans up effects from the previous render before running the effects next time.”
React Class uses a separate method “componentDidUpdate” to handle updates in props & if need to clean any state, we can do that in this method before applying new props But in the Functional component, there is no special code for handling updates because useEffect handles them by default, so it cleans up the previous effects in every re-render before applying the next effects.

Read more here >

💡 What are the rules to use Hooks?

  • Only Call Hooks at the Top Level: Don’t call Hooks inside loops, conditions, or nested functions.
  • Only Call Hooks from React Functions or from Custom Hooks: Don’t call Hooks from regular JavaScript functions.

💡 Is there any limitation on props?

There are no limitations on what you can pass as props in React. You can pass any data or any Component object into this.
In the below code, React elements like “Contacts” and “Chat” are just objects, so you can pass them as props like any other data.

        <Contacts />
        <Chat />

// Panel component
function Panel(props) {
  return (
      <div className="Panel-left">
        {props.left} // using component that coming in props
      <div className="Panel-right">

💡 What is the meaning of Composition in React?

React has a powerful Composition model, and It recommends using composition instead of inheritance to reuse code between components.
Component composition is a powerful pattern to make your components more reusable. Composition is the act of combining parts or elements to form a whole.
In react, the Component composition is passing components as props to other components, thus creating new components with other components. See the above code snippet.
If you only want to avoid passing some props through many levels, the component composition is often a simpler solution than context API.

React JS Interview Questions and Answers

💡 What is the meaning of prop drilling?

Prop drilling is the act of passing props through multiple layers of components.

💡 What is Context API?

The new React Context API, introduced with React v.16.3, allows us to pass data through our component trees, giving our components the ability to communicate and share data at different levels.

const MyContext = React.createContext(defaultValue); // Initialize context

<MyContext.Provider value={/* some value */}>

  {value => /* render something based on the context value */}

Provider -

Every Context object comes with a Provider. The Provider component accepts a value prop to be passed to consuming components that are descendants of this Provider. One Provider can be connected to many consumers. Providers can be nested to override values deeper within the tree.

Consumer -

All consumers that are descendants of a Provider will re-render whenever the Provider’s value prop changes. The propagation from Provider to its descendant consumers (including .contextType and useContext) is not subject to the shouldComponentUpdate method, so the consumer is updated even when an ancestor component skips an update.
Consumer requires a function as a child. The function receives the current context value and returns a React node.

If needed, you can watch the video >

💡 Explain useContext?

If you’re familiar with the context API before Hooks, useContext(MyContext) is equivalent to static contextType = MyContext in a class, or to MyContext.Consumer.
useContext(MyContext) only lets you read the context and subscribe to its changes. You still need a MyContext.Provider above in the tree to provide the value for this context.

const ThemeContext = React.createContext({}); // create context
const theme = useContext(ThemeContext); // use context

💡 What is the difference between useCallback and useMemo Hooks?

useCallback and useMemo both expect a function and an array of dependencies. The difference is that useCallback returns its function when the dependencies change while useMemo calls its function and returns the result.
Since JavaScript has first-class functions, useCallback(fn, deps) is equivalent to useMemo(() => fn, deps). First Class function means in JavaScript is that you can assign a function to a value.

const memoizedValue = useMemo(() => computeExpensiveValue(a, b), [a, b]);

const memoizedCallback = useCallback(() => { doSomething(a, b); }, [a, b] );

💡 What is difference between createRef() & useRef()?

this.myRef = React.createRef(); // create ref
const node = this.myRef.current; // get current element
 render() {
    return <div ref={this.myRef} />; // bind in Template

const inputEl = useRef(null); // create ref
<input ref={inputEl} type="text" /> // bind in template
inputEl.current.focus(); // get current element

useRef: The useRef is a hook that uses the same ref throughout. It saves its value between re-renders in a functional component and doesn’t create a new instance of the ref for every re-render. It persists the existing ref between re-renders.

createRef: createRef is a function that generates a new ref each time it is called. Unlike the useRef, it does not save its value between re-renders, instead creates a new instance of the ref for every re-render. Thus implying that it does not persist the existing ref between re-renders.

💡 What is the difference between useEffect and useLayoutEffect?

useLayoutEffect method has the same signature as useEffect.
useEffect fires asynchronously after all DOM loading is done means after DOM painted. In other words, we can say useEffect runs asynchronously and after a render is painted to the screen.

useLayoutEffect hook on the other hand is invoked synchronously before changes are painted on the screen. In other words, we can say useLayoutEffect, runs synchronously after a render but before the screen is updated.
useLayoutEffect is useful for synchronously re-rendering the DOM but to prevent blocking the page loading, we should always use useEffect hook.
useLayoutEffect runs before the useEffect runs.

💡 What is the difference between Custom hooks and JS functions?

React Hooks are JS functions with the power of react, which means that you can add some logic that you could also add into a normal JS function, but also you will be able to use the native hooks like useState, useEffect, etc, to power up that logic, to add it state, or add it side effects, memoization or more. So I believe hooks are a really good thing to manage the logic of the components in an isolated way.

💡 What error comes if we use useState inside a JS function?

// Normal js function that using useState hook
const getMonth = () => {
     const [month, setMonth] = useState(0);
    useEffect(() => {
        const date = new Date();
    return month;

React Hook “useState” is called in the function “getMonth” which is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter react-hooks/rules-of-hooks.
Failed to compile.

💡 Write a Custom hook for the above same code –

import {useEffect, useState} from 'react';

 const useMonth = () =>{
    const [month, setMonth] = useState(0);
    useEffect(() => {
        const date = new Date();
    return [month];
export default useMonth;

💡 What is HOC in react?

A pattern is where a function takes a component as an argument and returns a new component.

const EnhancedComponent = higherOrderComponent(WrappedComponent);

Note that a HOC doesn’t modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC composes the original component by wrapping it in a container component. A HOC is a pure function with zero side effects.

Read here for more on HOC –
Higher Order Component with Functional Component | React JS

💡 What are the types of higher-order components?

Basically, there are two main types of HOC implementation: Props Proxy and Inheritance Inversion.
Read here for more info –

💡 What is the difference between Presentational and Container Components?

A common programming pattern in React is to have presentational and container components.
Container components contain business logic (methods) and handle state. Container components are also called Smart components. They serve as a bridge between the normal components that render the UI and the logic that makes the UI components interactive and dynamic.
Presentational components render that behavior and state to the user. They are also known as UI Components or Dumb Components. In React, a presentational component is a component that just renders HTML. The component’s only function is presentational markup.

💡 What is the use of prop types?

In React, the propTypes property can be used to perform type-checking on props. This gives developers the ability to set rules on what data/variable type each component prop should be and to display warnings when a component receives invalid type props.

import PropTypes from 'prop-types'.

// Some important proptypes - 

💡 What is the Prop type to select specific values?

optionalEnum: PropTypes.oneOf(['News', 'Photos']);

💡 What are Prop types to select one of many types?

optionalUnion: PropTypes.oneOfType([

💡 What is the difference between Controlled vs. Uncontrolled Form Fields?

In React, form fields are considered either Uncontrolled, meaning they maintain their own state, or Controlled, meaning that some parent maintains their state and passes it to them to display. Usually, the form fields will be controlled.

In a controlled component, form data is handled by a React component. The alternative is uncontrolled components, where form data is handled by the DOM itself.

To write an uncontrolled component, instead of writing an event handler for every state update, you can use a ref to get form values from the DOM.

💡 Which Form Control is always an Uncontrolled component?

In React, an <input type="file" /> is always an uncontrolled component because its value can only be set by a user, and not programmatically.

React JS Interview Questions & Answers

💡 Can we call setState inside render?

You should not setState() (modify the state) inside the render() method as it will result in an infinite loop. This is because the component calls the render() method when the state changes. Therefore, if you update the state inside this method, the component would keep calling the render() method infinitely.

💡 What are Fragments?

A common pattern in React is for a component to return multiple elements. Fragments let you group a list of children without adding extra nodes to the DOM.

💡 What are Keyed Fragments?

Fragments declared with the explicit <React.Fragment> Syntax may have keys. The key is the only attribute that can be passed to Fragment. A use case for this is mapping a collection to an array of fragments — for example, to create a description list:

function Glossary(props) {
  return (
      { => (
        // Without the `key`, React will fire a key warning
        <React.Fragment key={}>

💡 What is the difference between props and state?

props (short for “properties”) and state is both plain JavaScript objects. While both hold information that influences the output of render, they are different in one important way –
props get passed to the component (similar to function parameters) whereas the state is managed within the component (similar to variables declared within a function.

💡 What is the importance of using StrictMode?

  • Identifying components with unsafe lifecycles
  • Warning about legacy string ref API usage
  • Warning about deprecated findDOMNode usage
  • Detecting unexpected side effects
  • Detecting legacy context API
  • Ensuring reusable state

Leave a Reply

Your email address will not be published.