DEV Community

Opeyemi Odunayo
Opeyemi Odunayo

Posted on

Tech interview

Can you tell me about yourself?"/ "Tell me something about yourself.

  1. Start with a Brief Introduction: For example, "My name is [Your Name]. I grew up in [Your City/Town] and recently graduated with a degree in [Your Field]."
  2. Highlight Relevant Experience: Focus on skills and achievements that showcase your ability to excel in the role. For instance, "During my internship at [Company Name], I gained hands-on experience in [relevant skill], which I believe would be valuable in this role."
  3. Emphasize Skills and Strengths: Discuss any technical skills, soft skills, or certifications that make you a strong candidate. Provide examples of how you've used these skills to solve problems or achieve success in the past. For example, "I'm proficient in [relevant software/tools] and have strong problem-solving skills, which I demonstrated when I [specific example]."
  4. Express Passion and Motivation: Share why you're interested in the role and how it fits into your career goals. Convey enthusiasm and eagerness to contribute to the company's success. For instance, "I'm incredibly passionate about [industry/field], and I'm excited about the opportunity to [specific aspect of the job]. I'm eager to learn and grow in this role."
  5. Wrap Up with a Positive Note: For example, "Thank you for allowing me to share a bit about myself. I'm looking forward to discussing how my experiences and skills can contribute to the team's success."

Static Website: A website with fixed content that doesn't change unless manually updated. Dynamic Website: A website where content is generated or updated in real time, often using a database.

HTML Elements: Building blocks like div, p, h1, img, a, ul, ol, form, etc.

<head> Tag: Contains metadata (title, styles, scripts, etc.) for the webpage, not displayed in the body.

<body> Element: Contains all visible content on the webpage, such as text, images, and links.

Types of Listings in HTML:
ul (unordered list) ol (ordered list)dl (description list)

Difference Between ul and ol: ul: Unordered list, items are marked with bullets. ol: Ordered list, items are numbered.

Types of Headings: Ranges from h1 (largest) to h6 (smallest).

Semantic Elements: HTML tags like header, footer, article, and section that provide meaning to the web page's structure.

Why Use Semantic Elements: They improve accessibility, SEO, and make the code more readable.

justify-content in CSS: Aligns flex items along the main axis (e.g., left, center, right, space-between, space-around).

3 Ways of Writing CSS:
Inline styles, Internal styles within style, tag External styles linked CSS file.

Grid: A CSS layout system for creating flexible, grid-based layouts with rows and columns.

Universal Selector *: Selects all elements on the webpage.
Pseudo-Classes: Keywords added to selectors to style an element in a particular state, like :hover or :focus.

Pseudo-Elements: Used to style parts of an element, like ::before or ::after.

Box Element: In CSS, every element is treated as a box with properties like padding, margin, and border.

Fill Area: Expanding an element to fill available space, often using flex-grow or CSS Grid.

Types of Selectors: Universal *, Type p, Class .class, ID #id, Attribute attr, Descendant div p,

Types of Layout: Block, Inline, Flexbox, Grid

JavaScript: A programming language used to make web pages interactive.

Single or Multi-Threaded: JavaScript is a single-threaded language, but it uses asynchronous features for non-blocking tasks.

Data Types in JS:
Primitive: string, number, boolean, null, undefined, symbol, bigint
Non-Primitive: object, array, function

Two Main Data Types: Primitive, Non-Primitive.
String: A sequence of characters enclosed in quotes "text", 'text'.

The reduce function in JavaScript is an array method used to reduce an array to a single value by applying a callback function to each element of the array, one at a time, from left to right.

// An array of numbers
const data = [1, 2, 3, 4, 5];

// Using the reduce method to sum up the array elements
const sum = data.reduce((acc, num) => {
  // acc: accumulator, starts at 0 (the initial value)
  // num: the current number being processed
  return acc + num; // add the current number to the accumulator
}, 0); // initial value of acc is set to 0

console.log(sum); // Output: 15
Enter fullscreen mode Exit fullscreen mode
const result = false || 0 || null; // ans = null
Enter fullscreen mode Exit fullscreen mode

The || (logical OR) operator returns the first truthy value or the last falsy value if none are truth.

const result = false || 1 || null; // ans = 1
Enter fullscreen mode Exit fullscreen mode
const result = ["mango", "grape", "apple", "banana"];
delete result[2];
console.log(result); // ['mango', 'grape', empty, 'banana']
Enter fullscreen mode Exit fullscreen mode

The output ['mango', 'grape', empty, 'banana'] occurs because when you use the delete operator on an array element, it creates a "hole" in the array, resulting in an empty slot. This is why the console shows empty instead of undefined or another value.

Hoisting: is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase, before the code is executed. This means that you can use functions and variables before you actually declare them in the code

console.log(add(4, 6)); // ans = 10
function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

You can call add before its definition, and it will work fine.
Result: The call console.log(add(4, 6)); works correctly because add is hoisted

console.log(sub(4, 6)); // main.js:14 Uncaught ReferenceError: Cannot // access 'sub' before initialization
    at
let sub = (a, b) => {
  return a - b;
};
Enter fullscreen mode Exit fullscreen mode

Error: The call console.log(sub(4, 6)); throws an error (ReferenceError or TypeError) because sub is not initialized at the time it's called. Variables declared with let (or const) are hoisted but not initialized.

console.log(sub(4, 6));
// Uncaught TypeError: sub is not a function
var sub = (a, b) => {
  return a - b;
};
Enter fullscreen mode Exit fullscreen mode

Variable Hoisting: When using var, the declaration of the variable (sub) is hoisted to the top of its scope, but the initialization (the assignment of the arrow function) is not. This means that sub will exist in the scope but will be undefined until the line where the function is assigned is executed.

if (!data) sendBread();
var data = true;
function sendBread() {
  console.log("i am ready to send bread"); // I am ready to send bread
}
Enter fullscreen mode Exit fullscreen mode

The declaration of data is hoisted, but its initialization happens later in the code. Therefore, at the time of the if check, data is undefined.
Because of this, the if (!data) condition evaluates to true, leading to the call to sendBread(), which prints the message to the console.

console.log(1 - "2"); // ans -1
console.log(1 + "2");  // ans 12
Enter fullscreen mode Exit fullscreen mode

The - operator forces numeric conversion, resulting in subtraction.
The + operator with a string leads to string concatenation, producing a combined string result.


console.log(false == 0); // type coercion ans = true
console.log(false === 0); // no type coercion ans = false
Enter fullscreen mode Exit fullscreen mode

Use == when you want to compare values for equality with type coercion, but be cautious as it can lead to unexpected results due to implicit conversions.
Use === when you want to compare both the value and type without any coercion, ensuring a stricter comparison. This is generally recommended to avoid unintended type conversion issues.

console.log(typeof null); // null is an object
Enter fullscreen mode Exit fullscreen mode
const numbers = [4, 1, 2, 7];
numbers.sort();
console.log(numbers[2]); // ans = 4
Enter fullscreen mode Exit fullscreen mode

When you call numbers.sort(), the sorting process converts each number to a string:

4 becomes "4", 1 becomes "1", 2 becomes "2", 7 becomes "7"
The Unicode order sorts them as follows:
"1", "2", "4", "7"
In the sorted array, numbers[2] refer to the third element (since arrays are zero-indexed).

difference between var and let in javascript
var is function-scoped, meaning that when a variable is declared with var inside a function, it is accessible throughout the entire function, regardless of where it is declared within the function.
If var is declared inside a function, the variable will not be accessible outside the function.

function example() {
  var x = 10;   // Declared inside the function
  if (true) {
    var y = 20; // y is still function-scoped, even though it's inside an if-block
  }
  console.log(x); // 10 (x is accessible anywhere inside the function)
  console.log(y); // 20 (y is accessible too, even though it was declared in the block)
}

example();

console.log(x); // ReferenceError: x is not defined (x is not accessible outside the function)
console.log(y); // ReferenceError: y is not defined (y is not accessible outside the function)
Enter fullscreen mode Exit fullscreen mode

let is block-scoped, meaning that variables declared with let are confined to the block in which they are defined. A block is typically enclosed by curly braces {} in structures like if, for, or function bodies.

function example() {
  let x = 10;   // Declared in the function, accessible within the function

  if (true) {
    let y = 20; // y is block-scoped, only accessible within this block
    console.log(y); // 20 (y is accessible inside the block)
  }

  console.log(x); // 10 (x is accessible inside the function)
  console.log(y); // ReferenceError: y is not defined (y is not accessible outside the block)
}

example();
Enter fullscreen mode Exit fullscreen mode

CSS flex and grid
Flexbox is primarily designed for one-dimensional layouts,
either in a row or a column
when to use: Simple Row/Column Layouts:
If your layout requires arranging items in a single row or
column.

CSS Grid Layout is a two-dimensional system designed for
creating complex grid-based layouts. It allows us to define
both rows and columns and place items at precise locations
within this grid
When to Use CSS Grid:

  1. Complex Layouts: If your layout requires a multi-dimensional grid structure, such as magazine layouts or intricate card designs.
  2. Multi-Column and Multi-Row Forms: When designing forms with multiple columns or rows

JSX is like a more powerful version
of HTML that plays really well with JavaScript, especially
in React apps. It helps make your web pages interactive and
dynamic.

Callbacks are functions that are passed as arguments to other functions and are executed after a certain event occurs or a specific condition is met

// Define a function named greet that takes a name and a callback function as parameters
function greet(name, callback) {
  console.log(`Hello, ${name}!`);  // Logs a greeting message using the provided name
  callback(); // Calls the callback function
}

// Define a function named sayGoodbye that logs a goodbye message
function sayGoodbye() {
  console.log("Goodbye!");
}

// Pass the sayGoodbye function as a callback to the greet function
greet("Alice", sayGoodbye); // Expected output: "Hello, Alice!" followed by "Goodbye!"
Enter fullscreen mode Exit fullscreen mode

Event delegation is a programming pattern in JavaScript
where a single event listener is used to manage all
occurrences of a particular event type for multiple elements,
usually within a common parent container.
How it works:
Instead of attaching an event listener to each individual child
element, you attach a single event listener to a common
ancestor (typically a parent element) that contains all the
child elements.

Problem: Write a function that checks if two strings are anagrams (contain the same characters in a different order).
Anagrams are words or phrases that are formed by rearranging the letters of another word or phrase, using all the original letters exactly once. For example:
The word "listen" can be rearranged to form "silent.

function areAnagrams(str1, str2) {
    const normalize = str => str.replace(/[^a-z]/gi, '').toLowerCase().split('').sort().join('');
    return normalize(str1) === normalize(str2);
}
// Example Usage:
console.log(areAnagrams("listen", "silent")); // Output: true
Enter fullscreen mode Exit fullscreen mode

Problem: Write a function to reverse a given string.

function reverseString(str) {
    return str.split('').reverse().join('');
}
// Example Usage:
console.log(reverseString("hello")); // Output: "olleh"
Enter fullscreen mode Exit fullscreen mode

Problem: Write a function that checks if a given string is a palindrome (reads the same backward as forward).

function isPalindrome(str) {
    const cleanedStr = str.replace(/[^a-z0-9]/gi, '').toLowerCase();
    return cleanedStr === cleanedStr.split('').reverse().join('');
}

// Example Usage:
console.log(isPalindrome("A man, a plan, a canal, Panama")); // Output: true
Enter fullscreen mode Exit fullscreen mode

Problem: Write a function that returns the largest number in a given array of numbers.

function findLargestNumber(arr) {
    return Math.max(...arr);
}
// Example Usage:
console.log(findLargestNumber([3, 5, 1, 8, 2])); // Output: 8
Enter fullscreen mode Exit fullscreen mode

write a function to Count Consonants in a String

function countConsonants(str) {
  // Define a set of vowels for quick reference
  const vowels = new Set(['a', 'e', 'i', 'o', 'u']);

  // Initialize a counter to keep track of consonants
  let consonantCount = 0;

  // Convert the string to lowercase to make the function case-insensitive
  for (let char of str.toLowerCase()) {
    // Check if the character is a letter and not a vowel
    if (/[a-z]/.test(char) && !vowels.has(char)) {
      consonantCount++; // Increment the consonant count
    }
  }
  // Return the total count of consonants found in the string
  return consonantCount;
}
// Example usage
console.log(countConsonants("Hello World!")); // Expected output: 7
Enter fullscreen mode Exit fullscreen mode

Write a function to Remove Duplicates from an Array

function removeDuplicates(arr) {
  // Use filter to keep only unique items
  return arr.filter((item, index) => 
    // Check if the current item's index is the first occurrence of the item
    arr.indexOf(item) === index
  );
}
// Example usage
console.log(removeDuplicates([1, 2, 2, 3, 4, 4, 5]));
 // Output: [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

A Promise is an object representing a future value or completion/failure of an asynchronous operation. It has three states: pending, fulfilled, and rejected. The .then() and .catch() methods handle the result.
async/await is syntactic sugar over Promises, making asynchronous code look more like synchronous code. It uses async functions, where await pauses code execution until the Promise resolves or rejects.

Extracting Year, Month, and Hour from an ISO Date String
This code snippet demonstrates how to split an ISO 8601 date string into its components and extract the year, month, and hour

const dateParts = new Date().toISOString().split(/[-T:]/);
const [year, month, hour] = dateParts;
console.log(year, month, hour);
Enter fullscreen mode Exit fullscreen mode
const numbers = [7, 3, 26];
numbers.sort();
console.log(numbers);
Enter fullscreen mode Exit fullscreen mode

The .sort() method, when used without a compare function, sorts the array elements as strings. Therefore:
26 as a string ("26") comes before "3" because the first character ("2") has a lower code point than "3".
"3" comes before "7" in Unicode order.

REACT
What is React?
React is a JavaScript library developed by Facebook for building user interfaces, specifically single-page applications. It allows developers to build reusable components, manage application state, and update the UI efficiently with a virtual DOM.

  1. What are components in React? Components are the building blocks of a React application. They are reusable, self-contained pieces of UI that can be nested, managed, and handled independently.
  2. What is the difference between a functional component and a class component?
    Class components use ES6 classes, have lifecycle methods, and manage their own state via this.state.
    Functional components are simpler JavaScript functions that can use useState and other hooks to manage state and lifecycle without needing classes.

  3. What is JSX?
    JSX stands for JavaScript XML. It allows writing HTML-like syntax directly in JavaScript, which React then transforms into JavaScript calls to create UI elements.

  4. Explain the concept of state and props in React.
    State is a component's local data that can change over time, while props are inputs to a component passed from its parent, used for rendering dynamic content.

  5. What are React Hooks?
    Hooks are functions introduced in React 16.8 that let you use state and other React features in functional components. Common hooks include useState, useEffect, and useContext.

  6. What is the virtual DOM?
    The virtual DOM is an in-memory representation of the actual DOM. React uses it to optimize DOM manipulation by re-rendering only the components that changed, instead of updating the whole DOM.

  7. What is useState and how does it work?
    useState is a hook that allows functional components to have state variables. It returns an array with the current state and a function to update it.

  8. Explain useEffect and its dependencies.
    useEffect is a hook for performing side effects (like fetching data or updating the DOM). Its dependency array controls when the effect runs; it runs whenever a dependency value changes.

  9. What are controlled and uncontrolled components?
    Controlled components are inputs whose values are managed by React state.
    Uncontrolled components store their own state in the DOM, which is accessed via ref in React.

  10. What is Context API in React, and how do you use it?
    The Context API allows you to pass data through the component tree without manually passing props. It’s ideal for global state or theme management.
    syntax explanation
    Context Setup with GlobalContextProvider

import { createContext, useState } from "react";
// Creating GlobalContext for sharing theme and toggle function across the app
export const GlobalContext = createContext();
// GlobalContextProvider component provides theme and thoggleMode to its children
export const GlobalContextProvider = ({ children }) => {
  // State to manage theme, initially set to 'dark'
  const [theme, setTheme] = useState("dark");

  // Toggle function to switch between 'light' and 'dark' themes
  const thoggleMode = () => {
    setTheme((prevTheme) => (prevTheme === "light" ? "dark" : "light"));
  };
  return (
    // Using GlobalContext.Provider to pass down theme and thoggleMode
    <GlobalContext.Provider value={{ theme, thoggleMode }}>
      {children} {/* Render children components with access to the context */}
    </GlobalContext.Provider>
  );
};
Enter fullscreen mode Exit fullscreen mode

main.jsx - Setting up the Application with GlobalContextProvider

import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import "./index.css";
import App from "./App.jsx";
import { GlobalContextProvider } from "./context.jsx";

// Root rendering where GlobalContextProvider wraps App
// This ensures that all components in App have access to GlobalContext
createRoot(document.getElementById("root")).render(
  <StrictMode>
    <GlobalContextProvider>
      <App />
    </GlobalContextProvider>
  </StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

App.jsx - Consuming Context in the App Component

import { useContext } from "react";
import { GlobalContext } from "./context";
const App = () => {
  // Destructuring theme and thoggleMode from GlobalContext
  const { theme, thoggleMode } = useContext(GlobalContext);
  return (
    <div className="flex items-center justify-center gap-3 flex-col mt- 
    20">
      {/* Heading with conditional classes based on theme state */}
      <h1
        className={`${
          theme === "light" ? "bg-black text-white" : "bg-red-700 text- 
     white"
        }`}
      >
        this text background will change from white to black same as 
       the text
        whenever the button is click
      </h1>

      {/* Button to toggle theme */}
      <button onClick={thoggleMode} className="bg-blue-600 p-3 rounded- 
       md">
        change theme
      </button>
    </div>
  );
};
export default App;
Enter fullscreen mode Exit fullscreen mode

Accessing Context Data: By using useContext(GlobalContext), we destructure theme and thoggleMode, making the state and function available directly in App.
Conditional Styling: The h1 element uses the value of theme to apply different classes based on whether the theme is light or dark. This changes the background and text color accordingly.
Button Click Handler: The button has an onClick event handler that calls thoggleMode, toggling the theme each time it’s clicked. This re-renders the component with the updated theme state.
This setup efficiently uses the Context API to manage the global theme state and toggle function without prop drilling, making it more scalable and easy to maintain.

  1. What is memo in React, and when should you use it? memo is a higher-order component that prevents re-renders if the props of a component don’t change, optimizing performance in certain cases.
  2. What is Redux, and how does it work with React? Redux is a state management library that allows you to manage and centralize application state. It uses a global store and dispatch actions to update the state.
  3. What is the significance of keys in React lists? Keys are unique identifiers for elements in lists to help React efficiently re-render lists by tracking each item.
  4. What is propTypes and how is it used? propTypes is a way to specify and validate the expected types of props passed to a component, enhancing error-checking and readability.
  5. What are higher-order components (HOCs)? HOCs are functions that take a component and return a new component, adding extra functionality to the wrapped component.
  6. What are the lifecycle methods in a React class component? Common lifecycle methods include: Mounting: constructor, componentDidMount Updating: shouldComponentUpdate, componentDidUpdate Unmounting: componentWillUnmount
  7. What is lazy loading in React? Lazy loading delays the loading of components or resources until they are needed, improving performance and load time.
  8. What is React Router, and how does it work? React Router is a library for routing in React applications. It enables navigation between different views or components and supports dynamic URL parameters.
  9. What is React.StrictMode? React.StrictMode is a wrapper component that activates additional checks and warnings for its children, helping developers find potential issues early.
  10. What is code splitting, and how does it work in React? Code splitting allows you to split your code into smaller bundles, loading only the necessary code when required. In React, this is commonly done with React.lazy and Suspense.
  11. What is reconciliation in React? Reconciliation is the process by which React updates the DOM by comparing the virtual DOM with a previous version and efficiently updating only the changed parts.
  12. What are fragments in React, and why are they useful? Fragments (... or <>...</>) allow you to group multiple elements without adding extra nodes to the DOM.
  13. What is useRef, and how is it used? In React, useRef is a hook (a special function) that helps you store values or references to DOM elements across different renders of your component. syntax explanation
const Hooks = () => {
  // Initialize a reference to store a reference to the input element.
  const inputRef = useRef(null);

  // Function to focus the input element when called.
  // `inputRef.current` will hold a reference to the DOM element if it exists.
  const focusInput = () => {
    if (inputRef.current) { // Check if `inputRef.current` is not null
      inputRef.current.focus(); // Focus on the input element using the ref
    }
  };
  return (
    <div>
      {/* Attach the ref to the input element.
          Now `inputRef.current` will hold a reference to this input element after the initial render. */}
      <input ref={inputRef} type="text" />

      {/* Button to trigger the focusInput function when clicked.*/}
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode
  1. What are portals in React? Portals provide a way to render components outside the main DOM hierarchy, useful for modals and tooltips that need to visually “break out” of their container.
  2. How does React handle forms? Forms can be controlled or uncontrolled. Controlled forms use React state to manage form data, while uncontrolled forms rely on the native DOM to handle form values.
  3. What is server-side rendering (SSR) in React? SSR renders React components on the server and sends a fully-rendered page to the client, improving initial load time and SEO.
  4. What is hydration in React? Hydration is the process of adding interactivity to static HTML generated by server-side rendering. The client-side JavaScript binds event listeners and updates the virtual DOM.
  5. What is React's Profiler, and how can it be used? The Profiler API measures rendering performance for components, helping identify bottlenecks in rendering.
  6. What is the purpose of React Fiber? React Fiber is the underlying algorithm used by React to manage reconciliation. It allows React to prioritize updates and split rendering work into segments, enhancing performance.

useReducer is useful for managing more complex or structured state changes in a React component. It's especially handy when you have a lot of "if-else" or "switch-case" logic to update the state based on different actions.

What's the difference between HTTP and HTTPS?
The primary difference between HTTP (Hypertext Transfer Protocol) and HTTPS (Hypertext Transfer Protocol Secure) is that HTTPS is secure while HTTP is not.
Key Differences Between HTTP and HTTPS:
HTTP: Transmits data in plain text, meaning information sent between the client (e.g., a browser) and server can be intercepted and read by attackers.
HTTPS: Encrypts data using SSL (Secure Sockets Layer) or TLS (Transport Layer Security), which makes it much harder for attackers to intercept and read sensitive information, like passwords or credit card details.
HTTP: Vulnerable to various attacks, such as man-in-the-middle (MITM) attacks, where an attacker could modify or intercept data.
HTTPS: Provides data integrity, authentication, and confidentiality, helping to protect users' sensitive information from being stolen or tampered with.

Problem: Create a component that filters a list of items based on search input.

const items = ["banana", "mango", "grape", "cashew", "cherries"];
  const [search, setSearch] = useState("");
  const filteredSearch = items.filter((item) => {
    return item.toLowerCase().includes(search.toLowerCase());
  });
  return (
    <>
      <div>
        <h1>FilterSearch</h1>
        <input
          className="bg-gray-600 rounded-md p-3 text-white outline:focus-none"
          type="text"
          onChange={(e) => setSearch(e.target.value)}
          value={search}
        />
        {filteredSearch.length > 0 ? (
          filteredSearch.map((item, index) => {
            return (
              <div key={index}>
                <h1>{item}</h1>
              </div>
            );
          })
        ) : (
          <h1>no item found</h1>
        )}
      </div>
    </>
  );
Enter fullscreen mode Exit fullscreen mode

axios vs fetch
axios has a simpler syntax, automatically stringifies JSON data when sending requests, and parses JSON data in responses. For example:

axios.post('/api/data', { key: 'value' })
  .then(response => console.log(response.data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

axios: Automatically rejects on HTTP errors (e.g., 4xx or 5xx status codes), making error handling straightforward.
fetch: Requires explicit JSON handling, meaning you often need to use JSON.stringify() for request payloads and response.json() for parsing JSON responses:

fetch('/api/data', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ key: 'value' })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

fetch: Does not reject HTTP errors by default; you need to check response.ok or the status code manually
When to Use Each?
Use axios when you need ease of use, robust error handling, built-in support for interceptors, and are working in a variety of JavaScript environments.

Use fetch if you prefer a lightweight native API, need fine-grained control, or want to minimize library dependencies.

How can you optimize web images in terms of file size and loading speed?
Choosing the Right Image Format:
Use modern image formats like WebP, JPEG 2000, or AVIF when possible.
These formats offer better compression and quality.
Resize Images:
Use tools like Photoshop, GIMP, or online services to resize images to the exact dimensions needed.
Avoid using larger images than necessary.
Enable Browser Caching:
Implement browser caching for images.
This reduces the need to download images on subsequent visits, enhancing loading speed.

A custom hook in React is a JavaScript function that allows you to reuse logic across multiple components. It’s a way to encapsulate and share stateful logic using React's built-in hooks (like useState, useEffect, etc.), without duplicating code. Custom hooks help you keep components clean and focused on rendering, while the custom hook manages the shared logic
How to Create a Custom Hook
To create a custom hook:
Define it as a JavaScript function — a custom hook is just a function that starts with use, for example, useFetchData.
Use built-in hooks inside it — like useState, useEffect, etc.
Return data or functions that the consuming component might need.
below is a syntax explanation
Here’s an example of a simple custom hook that fetches data from an API.

import { useState, useEffect } from "react";

const useFetchData = (url) => {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        const res = await fetch(url);
        if (!res.ok) {
          throw new Error("Network response was not ok");
        }
        const result = await res.json();
        setData(result);
      } catch (error) {
        setError(error);
      } finally {
        setLoading(false);
      }
    };
    fetchData();
  }, [url]);
  return { data, loading, error };
};
export default useFetchData;
Enter fullscreen mode Exit fullscreen mode

Now, you can use the useFetchData custom hook in any component that needs to fetch data from a given URL.

import React from 'react';
import useFetchData from './useFetchData';
function DataDisplay() {
  const { data, loading, error } = useFetchData('https://api.example.com/data');
  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;
  return (
    <div>
      {data && data.map(item => (
        <div key={item.id}>{item.name}</div>
      ))}
    </div>
  );
}
export default DataDisplay;
Enter fullscreen mode Exit fullscreen mode

General Question
What is a Software Framework and why should we use one?
In software dev., a framework gives devs a pre-built structure with tools, libraries, and best practices, so they don’t have to start from scratch,
Using a framework saves time and effort. Instead of reinventing the wheel, devs can leverage the framework’s built-in features to handle common tasks like user authentication, and routing.
This allows them to focus on what makes their application unique.

"What is the difference between null and undefined?"
undefined: When a variable is declared but not initialized, it automatically gets assigned the value undefined. If you try to access an object property that doesn't exist, you get undefined.
null: It is a value that represents the intentional absence of any object value. You can explicitly assign a variable or object property the value null to indicate no value or no object. It is often used to indicate that a variable or object property should have no value or that the value is unknown or irrelevant.

Mention five ways to decrease page load time.
Optimize Images:Images are often the largest assets on a web page, and unoptimized images can significantly slow down load times.
Minify and Combine Files:
HTML, CSS, and JavaScript files can contain unnecessary whitespace, comments, and redundant code which increase their size.

What is the difference between multitasking and multiprocessing OS?
Multitasking: This refers to an operating system's ability to handle multiple tasks (or processes) simultaneously. In a multitasking OS, a single CPU switches rapidly between different tasks, giving the illusion that they are running at the same time.

Multiprocessing: This involves an operating system that can use more than one CPU (or core) at the same time. In a multiprocessing OS, different tasks can truly run concurrently on different processors.

What ways can we test our frontend APP?
Unit Testing
Purpose: Test individual components in isolation.
Tools:
Jest: A popular testing framework for JavaScript and TypeScript.
React Testing Library: Focuses on testing React components.
Example: Testing a button component to ensure it triggers the correct function

Top comments (0)