Most Frequently Asked Front-end Interview Questions

mursalfk

Mursal Furqan Kumbhar

Posted on August 4, 2024

Most Frequently Asked Front-end Interview Questions

Hello, Amazing Devs 👋

Did you recently graduate? Are you planning to switch your job? Are you planning to take another of those difficult technical interviews about front-end development?

Well, it's your lucky Sunday 😍

Today we will discuss some of the most frequently asked front-end interview questions and their answers. P.S. Brace yourselves. It's going to be a long post today 😉

HTML

1. What is the purpose of the aria-label attribute in HTML?

The aria-label attribute is used to provide a string that labels an element. It is particularly useful for accessibility purposes, allowing screen readers to announce the label when users interact with the element. This attribute is often used when an element does not have visible text content but still needs to be described.

<button aria-label="Close">X</button>
Enter fullscreen mode Exit fullscreen mode

In this example, a screen reader will read "Close" when it encounters the button, even though the visible text is just "X".

2. Describe the difference between a div and a span in HTML.

  • div: A div (short for "division") is a block-level element used to group other block-level and inline elements. It creates a new line before and after its content, taking up the full width available.
  <div>
    <p>This is a block element.</p>
    <p>It creates a line break before and after its content.</p>
  </div>
Enter fullscreen mode Exit fullscreen mode
  • span: A span is an inline element used to group inline elements or text. It does not create a new line before or after its content and only takes up as much width as necessary.
  <p>This is a <span>span element</span> inside a paragraph.</p>
Enter fullscreen mode Exit fullscreen mode

3. What is the difference between client-side and server-side rendering?

  • Client-side rendering (CSR):
    • Content is rendered in the browser using JavaScript.
    • The initial HTML sent from the server is minimal.
    • JavaScript fetches data and builds the content dynamically.
    • Benefits: Rich interactions and faster subsequent page loads.
    • Drawbacks: Slower initial load time and may impact SEO.
  // React Example (CSR)
  import React, { useState, useEffect } from 'react';

  function App() {
    const [data, setData] = useState(null);

    useEffect(() => {
      fetch('/api/data')
        .then(response => response.json())
        .then(data => setData(data));
    }, []);

    return (
      <div>
        {data ? <p>{data.message}</p> : <p>Loading...</p>}
      </div>
    );
  }

  export default App;
Enter fullscreen mode Exit fullscreen mode
  • Server-side rendering (SSR):
    • Content is rendered on the server and sent to the client as a complete HTML page.
    • The initial load is faster because the browser receives a fully rendered page.
    • Benefits: Faster initial load and better SEO.
    • Drawbacks: Potentially slower interactions after the initial load due to additional server requests.
  // Next.js Example (SSR)
  import React from 'react';

  function Home({ data }) {
    return (
      <div>
        <p>{data.message}</p>
      </div>
    );
  }

  export async function getServerSideProps() {
    const res = await fetch('https://api.example.com/data');
    const data = await res.json();
    return { props: { data } };
  }

  export default Home;
Enter fullscreen mode Exit fullscreen mode

4. What are Data Attributes?

Data attributes are custom attributes that start with data- and allow you to store extra information on HTML elements. This information can be accessed and manipulated using JavaScript, making it useful for adding metadata to elements that can be read and used in scripts.

<div data-user-id="12345" data-role="admin">User Info</div>
<script>
  const element = document.querySelector('div');
  const userId = element.getAttribute('data-user-id');
  const role = element.getAttribute('data-role');
  console.log(userId); // Outputs: 12345
  console.log(role);   // Outputs: admin
</script>
Enter fullscreen mode Exit fullscreen mode

5. Can you explain the purpose of the <!DOCTYPE> declaration at the beginning of an HTML document?

The <!DOCTYPE> declaration is used to specify the document type and version of HTML being used. It ensures that the browser renders the page in standards mode, which adheres to the HTML specification. Without it, browsers may enter quirks mode, which emulates older browser behaviors and can lead to inconsistent rendering.

<!DOCTYPE html>
<html>
<head>
  <title>Document</title>
</head>
<body>
  <p>Hello, world!</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

6. What is semantic HTML, and why is it important?

Semantic HTML refers to the use of HTML elements that convey meaning about the content they enclose. Examples include <header>, <article>, <section>, <footer>, and <nav>. Using semantic HTML enhances the accessibility of web pages, improves SEO, and makes the code more readable and maintainable.

<article>
  <header>
    <h1>Article Title</h1>
    <p>Published on: <time datetime="2024-01-01">January 1, 2024</time></p>
  </header>
  <section>
    <p>This is the content of the article.</p>
  </section>
  <footer>
    <p>Author: John Doe</p>
  </footer>
</article>
Enter fullscreen mode Exit fullscreen mode

7. How can you include an external CSS file in an HTML document?

You can include an external CSS file using the <link> tag within the <head> section of your HTML document. The href attribute specifies the URL of the CSS file.

<!DOCTYPE html>
<html>
<head>
  <title>My Page</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <p>Hello, world!</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

8. What is the purpose of the <meta> tag in HTML?

The <meta> tag provides metadata about the HTML document. It can specify the character set, viewport settings, author, description, keywords, and other information relevant to the document. This metadata is not displayed on the page but can be used by browsers, search engines, and other web services.

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="A brief description of the page">
  <title>My Page</title>
</head>
<body>
  <p>Hello, world!</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

9. Explain the difference between the <section>, <article>, and <aside> tags.

  • <section>: Represents a generic section of a document, typically with a heading. It is used to group related content.
  <section>
    <h2>Section Title</h2>
    <p>This is a section of the document.</p>
  </section>
Enter fullscreen mode Exit fullscreen mode
  • <article>: Represents a self-contained piece of content that can be independently distributed or reused, such as a blog post, news article, or forum post.
  <article>
    <h2>Article Title</h2>
    <p>This is a self-contained article.</p>
  </article>
Enter fullscreen mode Exit fullscreen mode
  • <aside>: Represents content that is tangentially related to the main content. It is often used for sidebars, pull quotes, or advertisements.
  <aside>
    <h2>Related Information</h2>
    <p>This is related content, but not the main focus of the document.</p>
  </aside>
Enter fullscreen mode Exit fullscreen mode

10. How do you create a form in HTML?

A form in HTML is created using the <form> tag, which can contain various form elements such as <input>, <select>, <textarea>, <button>, and more. The action attribute specifies where to send the form data, and the method attribute specifies how to send the data (e.g., GET or POST).

<form action="/submit" method="post">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <label for="email">Email:</label>
  <input type="email" id="email" name="email">
  <button type="submit">Submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

its not over yet

CSS

1. How do you debug CSS code?

To debug CSS code, you can use the following techniques:

  • Browser Developer Tools: Most modern browsers come with built-in developer tools. You can inspect elements, view and modify their styles, check the computed styles, and see the applied CSS rules.

    • Inspect Elements: Right-click on an element and select "Inspect" to see its HTML and CSS.
    • Computed Styles: View the final styles applied to an element.
    • Console: Look for errors or warnings related to CSS.
  • CSS Validators: Use online tools like the W3C CSS Validator to check for syntax errors.

  • Commenting Out: Temporarily comment out sections of CSS to isolate issues.

  • CSS Outlines: Add temporary outlines to elements to see their boundaries.

  * {
    outline: 1px solid red;
  }
Enter fullscreen mode Exit fullscreen mode

2. Describe the difference between specificity and inheritance in CSS.

  • **

Specificity**: Determines which CSS rule is applied when multiple rules could apply to the same element. Specificity is calculated based on the types of selectors used. The hierarchy is as follows (from lowest to highest specificity):

  • Type selectors (e.g., div, p)
  • Class selectors (e.g., .class)
  • Attribute selectors (e.g., [type="text"])
  • ID selectors (e.g., #id)
  • Inline styles (e.g., style="color: red;")
  /* Example of specificity */
  p { color: blue; }            /* Type selector - least specific */
  .class { color: green; }      /* Class selector */
  #id { color: red; }           /* ID selector - most specific */
Enter fullscreen mode Exit fullscreen mode
  • Inheritance: Some CSS properties are inherited from parent elements to child elements. For example, properties like color, font-family, and line-height are typically inherited.
  <div style="color: blue;">
    <p>This text is blue because it inherits the color from the parent div.</p>
  </div>
Enter fullscreen mode Exit fullscreen mode

3. How do you create a smooth scrolling effect using CSS?

You can create a smooth scrolling effect by using the scroll-behavior property.

html {
  scroll-behavior: smooth;
}
Enter fullscreen mode Exit fullscreen mode

This will enable smooth scrolling for all anchor links and other scrollable elements on the page.

4. What is the CSS box model?

The CSS box model describes the rectangular boxes generated for elements in the document tree and consists of the following parts (from the inside out):

  • Content: The actual content of the element (text, images, etc.).
  • Padding: The space between the content and the border. It is inside the element's background.
  • Border: The border surrounding the padding (if any) and content.
  • Margin: The space outside the border, separating the element from other elements.
div {
  width: 100px;
  padding: 10px;
  border: 5px solid black;
  margin: 20px;
}
Enter fullscreen mode Exit fullscreen mode

In this example, the total width of the div will be 150px (100px width + 10px padding on each side + 5px border on each side).

5. What is the purpose of the clearfix hack in CSS?

The clearfix hack is used to clear floats and ensure that a container element expands to encompass its floated children. Without clearfix, the parent container might collapse and not wrap around its floated child elements.

/* Clearfix hack */
.clearfix::after {
  content: "";
  clear: both;
  display: table;
}
Enter fullscreen mode Exit fullscreen mode

6. How do you center a div horizontally and vertically?

You can center a div horizontally and vertically using various methods, such as flexbox or CSS grid.

  • Flexbox:
  .container {
    display: flex;
    justify-content: center; /* Horizontal centering */
    align-items: center;     /* Vertical centering */
    height: 100vh;           /* Full viewport height */
  }
Enter fullscreen mode Exit fullscreen mode
  • CSS Grid:
  .container {
    display: grid;
    place-items: center;     /* Centers both horizontally and vertically */
    height: 100vh;
  }
Enter fullscreen mode Exit fullscreen mode

7. What are CSS preprocessors?

CSS preprocessors like Sass, Less, and Stylus extend the capabilities of CSS by adding features such as variables, nesting, mixins, and functions. These tools compile the preprocessed code into standard CSS, which can then be used in web projects.

  • Sass Example:
  $primary-color: #3498db;

  body {
    color: $primary-color;
  }

  .container {
    @include flex-center;
  }

  @mixin flex-center {
    display: flex;
    justify-content: center;
    align-items: center;
  }
Enter fullscreen mode Exit fullscreen mode

8. How can you make a responsive design using CSS?

Responsive design ensures that a website looks good on various devices and screen sizes. You can achieve this using media queries to apply different styles based on the screen width.

/* Example of media queries */
.container {
  display: flex;
}

@media (max-width: 600px) {
  .container {
    flex-direction: column;
  }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the layout changes from a horizontal to a vertical layout when the screen width is 600px or less.

9. What is the difference between absolute, relative, fixed, and sticky positioning in CSS?

  • Relative: Positioned relative to its normal position.
  .relative {
    position: relative;
    top: 10px; /* Moves 10px down from its original position */
  }
Enter fullscreen mode Exit fullscreen mode
  • Absolute: Positioned relative to its nearest positioned ancestor.
  .absolute {
    position: absolute;
    top: 10px; /* Moves 10px down from the nearest positioned ancestor */
  }
Enter fullscreen mode Exit fullscreen mode
  • Fixed: Positioned relative to the viewport and does not move when the page is scrolled.
  .fixed {
    position: fixed;
    top: 10px; /* Always 10px down from the top of the viewport */
  }
Enter fullscreen mode Exit fullscreen mode
  • Sticky: Switches between relative and fixed based on the scroll position.
  .sticky {
    position: sticky;
    top: 10px; /* Sticks to 10px from the top of the viewport when scrolled */
  }
Enter fullscreen mode Exit fullscreen mode

10. How do you use CSS variables?

CSS variables, also known as custom properties, allow you to store values that can be reused throughout your stylesheet. They are defined with the -- prefix and accessed using the var() function.

:root {
  --primary-color: #3498db;
  --padding: 10px;
}

body {
  color: var(--primary-color);
  padding: var(--padding);
}
Enter fullscreen mode Exit fullscreen mode

In this example, --primary-color and --padding are defined as custom properties and are reused in the body styles.

Half way there

JavaScript

1. What is memoization? Explain it with an example.

Memoization is an optimization technique used to speed up function calls by storing the results of expensive function calls and returning the cached result when the same inputs occur again. It helps to avoid redundant computations.

Example:

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

function slowFunction(num) {
  // Simulate a slow function
  for (let i = 0; i < 1e9; i++) {}
  return num * 2;
}

const memoizedSlowFunction = memoize(slowFunction);

console.log(memoizedSlowFunction(5)); // Computed
console.log(memoizedSlowFunction(5)); // Cached
Enter fullscreen mode Exit fullscreen mode

2. What is object destructuring?

Object destructuring is a syntax introduced in ES6 that allows you to extract properties from objects and bind them to variables. It provides a concise and readable way to extract values from objects.

Example:

const user = {
  name: 'John Doe',
  age: 30,
  email: 'john.doe@example.com'
};

const { name, age, email } = user;

console.log(name);  // Output: John Doe
console.log(age);   // Output: 30
console.log(email); // Output: john.doe@example.com
Enter fullscreen mode Exit fullscreen mode

3. How to handle exceptions/errors in JavaScript?

In JavaScript, you can handle exceptions using try...catch blocks. This allows you to catch errors and handle them gracefully, preventing the script from crashing.

Example:

try {
  // Code that may throw an error
  const result = riskyOperation();
  console.log(result);
} catch (error) {
  // Handle the error
  console.error('An error occurred:', error.message);
} finally {
  // Code that will always run, regardless of an error
  console.log('Cleanup operations');
}

function riskyOperation() {
  throw new Error('Something went wrong');
}
Enter fullscreen mode Exit fullscreen mode

4. What is throttling?

Throttling is a technique used to limit the number of times a function is executed over a period of time. It ensures that a function is called at most once within a specified interval, even if it is triggered multiple times.

Example:

function throttle(fn, wait) {
  let isThrottled = false;
  let lastArgs;

  return function(...args) {
    if (isThrottled) {
      lastArgs = args;
      return;
    }

    fn(...args);
    isThrottled = true;

    setTimeout(() => {
      isThrottled = false;
      if (lastArgs) {
        fn(...lastArgs);
        lastArgs = null;
      }
    }, wait);
  };
}

const throttledFunction = throttle(() => {
  console.log('Function called');
}, 2000);

window.addEventListener('resize', throttledFunction);
Enter fullscreen mode Exit fullscreen mode

5. Explain about event propagation.

Event propagation refers to the order in which events are captured and handled in the DOM. It includes three phases:

  • Capturing Phase: The event travels from the root to the target element.
  • Target Phase: The event reaches the target element.
  • Bubbling Phase: The event travels from the target element back up to the root.

Example:

<div id="parent" onclick="console.log('Parent Clicked')">
  <button id="child" onclick="console.log('Child Clicked')">Click Me</button>
</div>

<script>
  document.getElementById('child').addEventListener('click', (event) => {
    console.log('Child Event Listener');
    // Stop event propagation
    event.stopPropagation();
  });

  document.getElementById('parent').addEventListener('click', () => {
    console.log('Parent Event Listener');
  });
</script>
Enter fullscreen mode Exit fullscreen mode

In this example, clicking the button logs "Child Event Listener" and stops the event from propagating to the parent.

6. What are closures in JavaScript?

A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. Closures allow functions to access variables from an enclosing scope or environment.

Example:

function outerFunction() {
  const outerVariable = 'I am outside!';

  function innerFunction() {
    console.log(outerVariable);
  }

  return innerFunction;
}

const closure = outerFunction();
closure(); // Output: I am outside!
Enter fullscreen mode Exit fullscreen mode

In this example, innerFunction forms a closure that retains access to outerVariable even after outerFunction has finished executing.

7. What is the difference between let, const, and var?

  • var: Function-scoped or globally-scoped, can be re-declared, and is hoisted to the top of its scope.
  var a = 1;
  var a = 2; // No error
Enter fullscreen mode Exit fullscreen mode
  • let: Block-scoped, cannot be re-declared within the same scope, and is not hoisted.
  let b = 1;
  let b = 2; // Error
Enter fullscreen mode Exit fullscreen mode
  • const: Block-scoped, cannot be re-declared or re-assigned, and is not hoisted. Must be initialized during declaration.
  const c = 1;
  c = 2; // Error
Enter fullscreen mode Exit fullscreen mode

8. What is the difference between == and ===?

  • == (Loose Equality): Compares two values for equality after converting both values to a common type (type coercion).
  console.log(1 == '1'); // true
Enter fullscreen mode Exit fullscreen mode
  • === (Strict Equality): Compares two values for equality without converting their types (no type coercion).
  console.log(1 === '1'); // false
Enter fullscreen mode Exit fullscreen mode

9. How does async/await work in JavaScript?

async and await are syntactic sugar built on top of Promises to make asynchronous code look and behave more like synchronous code. An async function returns a Promise, and await is used to wait for the Promise to resolve.

Example:

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
Enter fullscreen mode Exit fullscreen mode

10. Explain the concept of this in JavaScript.

The value of this depends on the context in which a function is called. It can refer to different objects based on how the function is invoked:

  • Global Context: this refers to the global object (window in browsers).
  • Object Method: this refers to the object that owns the method.
  • Constructor Function: this refers to the newly created instance.
  • Arrow Function: this is lexically bound to the enclosing scope.

Example:

const obj = {
  name: 'John',
  greet: function() {
    console.log(this.name);
  }
};

obj.greet(); // Output: John

function ConstructorFunction(name) {
  this.name = name;
}

const instance = new ConstructorFunction('Jane');
console.log(instance.name); // Output: Jane
Enter fullscreen mode Exit fullscreen mode

imsssss

React

1. Explain the difference between class and functional components in React.

  • Class Components: Use ES6 classes, can hold and manage state using this.state, and have lifecycle methods (e.g., componentDidMount, shouldComponentUpdate).
  import React, { Component } from 'react';

  class MyComponent extends Component {
    constructor(props) {
      super(props);
      this.state = { count: 0 };
    }

    componentDidMount() {
      // Lifecycle method
    }

    render() {
      return (
        <div>
          <p>Count: {this.state.count}</p>
          <button onClick={() => this.setState({ count: this.state.count + 1 })}>
            Increment
          </button>
        </div>
      );
    }
  }

  export default MyComponent;
Enter fullscreen mode Exit fullscreen mode
  • Functional Components: Use functions, manage state with hooks (e.g., useState, useEffect), and are simpler and more concise.
  import React, { useState, useEffect } from 'react';

  function MyComponent() {
    const [count, setCount] = useState(0);

    useEffect(() => {
      // Similar to componentDidMount
    }, []);

    return (
      <div>
        <p>Count: {count}</p>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
    );
  }

  export default MyComponent;
Enter fullscreen mode Exit fullscreen mode

2. What is virtual DOM in React?

The virtual DOM is an in-memory representation of the actual DOM elements generated by React components. React maintains this virtual DOM to efficiently update the real DOM. When a component's state or props change, React creates a new virtual DOM, compares it with the previous virtual DOM using a process called "reconciliation," and only updates the actual DOM elements that have changed.

3. Explain the scenario when you use Redux.

Redux is used for state management in applications where the state needs to be shared and managed across multiple components. It is particularly useful in large applications with complex state interactions. Redux provides a predictable state container, making it easier to debug and test.

Scenarios to use Redux:

  • When multiple components need to access and update the same state.
  • When you want a single source of truth for the application state.
  • When the state management logic becomes too complex to handle with React's local state alone.

4. What are the various types of Hooks available in React?

React hooks allow functional components to use state and other React features. Some common hooks include:

  • useState: Manages state in functional components.
  • useEffect: Performs side effects in functional components (e.g., fetching data, subscribing to events).
  • useContext: Accesses context values without wrapping components in <Context.Consumer>.
  • useReducer: Manages state with a reducer function, useful for complex state logic.
  • useCallback: Memoizes functions to prevent unnecessary re-renders.
  • useMemo: Memoizes expensive calculations to optimize performance.
  • useRef: Creates a mutable object that persists across renders.

5. How to prevent re-renders in React?

To prevent unnecessary re-renders in React, you can use the following

techniques:

  • Memoization: Use React.memo for functional components and PureComponent for class components to memoize the component and prevent re-renders if the props have not changed.
  const MyComponent = React.memo(function MyComponent(props) {
    /* Render logic */
  });
Enter fullscreen mode Exit fullscreen mode
  • useCallback and useMemo: Memoize functions and values passed as props to prevent changes that trigger re-renders.
  const memoizedCallback = useCallback(() => {
    /* Function logic */
  }, [dependencies]);

  const memoizedValue = useMemo(() => {
    /* Expensive calculation */
  }, [dependencies]);
Enter fullscreen mode Exit fullscreen mode
  • shouldComponentUpdate: In class components, implement shouldComponentUpdate to control whether the component should re-render.
  class MyComponent extends React.Component {
    shouldComponentUpdate(nextProps, nextState) {
      return nextProps.value !== this.props.value;
    }

    render() {
      /* Render logic */
    }
  }
Enter fullscreen mode Exit fullscreen mode

6. How do you fetch data in React?

Data can be fetched in React using various methods, commonly with hooks or lifecycle methods:

  • useEffect: Fetch data in functional components.
  import React, { useState, useEffect } from 'react';

  function DataFetchingComponent() {
    const [data, setData] = useState(null);

    useEffect(() => {
      async function fetchData() {
        const response = await fetch('https://api.example.com/data');
        const result = await response.json();
        setData(result);
      }

      fetchData();
    }, []);

    return (
      <div>
        {data ? <p>{data.message}</p> : <p>Loading...</p>}
      </div>
    );
  }

  export default DataFetchingComponent;
Enter fullscreen mode Exit fullscreen mode
  • componentDidMount: Fetch data in class components.
  import React, { Component } from 'react';

  class DataFetchingComponent extends Component {
    state = { data: null };

    async componentDidMount() {
      const response = await fetch('https://api.example.com/data');
      const result = await response.json();
      this.setState({ data: result });
    }

    render() {
      return (
        <div>
          {this.state.data ? <p>{this.state.data.message}</p> : <p>Loading...</p>}
        </div>
      );
    }
  }

  export default DataFetchingComponent;
Enter fullscreen mode Exit fullscreen mode

7. Explain the concept of lifting state up in React.

Lifting state up involves moving state to a common ancestor component when multiple components need to share the same state. This ensures a single source of truth and prevents inconsistencies.

Example:
If two sibling components need to access the same state, lift the state up to their parent component.

function ParentComponent() {
  const [sharedState, setSharedState] = useState('');

  return (
    <div>
      <ChildComponent1 sharedState={sharedState} setSharedState={setSharedState} />
      <ChildComponent2 sharedState={sharedState} />
    </div>
  );
}

function ChildComponent1({ sharedState, setSharedState }) {
  return (
    <input
      type="text"
      value={sharedState}
      onChange={(e) => setSharedState(e.target.value)}
    />
  );
}

function ChildComponent2({ sharedState }) {
  return <p>Shared State: {sharedState}</p>;
}
Enter fullscreen mode Exit fullscreen mode

8. How do you handle forms in React?

Forms in React can be handled using controlled components, where form elements' values are controlled by the component's state.

import React, { useState } from 'react';

function FormComponent() {
  const [formData, setFormData] = useState({ name: '', email: '' });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setFormData({ ...formData, [name]: value });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    console.log(formData);
  };

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Name:
        <input type="text" name="name" value={formData.name} onChange={handleChange} />
      </label>
      <label>
        Email:
        <input type="email" name="email" value={formData.email} onChange={handleChange} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default FormComponent;
Enter fullscreen mode Exit fullscreen mode

9. What is the context API in React?

The Context API is a way to pass data through the component tree without having to pass props down manually at every level. It is useful for sharing global data like themes, authentication status, or user settings.

import React, { createContext, useContext, useState } from 'react';

const MyContext = createContext();

function App() {
  const [value, setValue] = useState('Hello, Context!');

  return (
    <MyContext.Provider value={value}>
      <ChildComponent />
    </MyContext.Provider>
  );
}

function ChildComponent() {
  const value = useContext(MyContext);
  return <p>{value}</p>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

10. What is Prop Drilling and how can you avoid it?

Prop drilling is the process of passing data from a parent component to deeply nested child components via props, which can become cumbersome and lead to hard-to-maintain code.

Ways to avoid prop drilling:

  • Context API: Share data without passing props through intermediate components.
  • State Management Libraries: Use libraries like Redux or MobX to manage state globally.

Example with Context API:

import React, { createContext, useContext, useState } from 'react';

const UserContext = createContext();

function App() {
  const [user, setUser] = useState({ name: 'John Doe' });

  return (
    <UserContext.Provider value={user}>
      <NestedComponent />
    </UserContext.Provider>
  );
}

function NestedComponent() {
  return <DeeplyNestedComponent />;
}

function DeeplyNestedComponent() {
  const user = useContext(UserContext);
  return <p>{user.name}</p>;
}

export default App;
Enter fullscreen mode Exit fullscreen mode

These questions and their detailed answers should help you prepare for front-end interviews, covering important concepts and practical examples in HTML, CSS, and React.

The end

Understanding these core JavaScript concepts and their practical applications is essential for any front-end developer. Whether it's mastering the art of memoization to optimize your functions, leveraging closures to maintain state, or handling asynchronous operations with ease using async/await, these skills form the foundation of effective and efficient web development.

As you continue to explore and experiment with these techniques, you'll enhance your problem-solving abilities and create more robust, performant, and maintainable applications. Keep pushing the boundaries of your knowledge, and let your passion for coding drive you to new heights in your front-end development journey.

Happy coding! 🚀

💖 💪 🙅 🚩
mursalfk
Mursal Furqan Kumbhar

Posted on August 4, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related