Job interview Flashcards
prepare for js interview
Create a ‘Like’ button with the following UI design and states - https://i.imgur.com/4JLyipM.png
Requirements
x - The button should show the text ‘Like’ and an icon to the left of the text.
x- The button should have gray text, icon and border.
x- When the user hovers over the button, the text, icon and border should turn red.
x- When the user clicks the button its state should toggle, the text and icon should turn white and the background colour should become red.
x- When the button is mounted it should call an API endpoint get the initial state (enabled or disabled).
- Clicking the button should call an API endpoint to update the new state (enabled or disabled).
- While the request is processing, the button should show a loading state.
*/—
import React, { useState, useEffect } from 'react'; import styles from './Button.module.css'; // Import CSS using CSS Modules const ButtonComponent = () => { const [isActive, setIsActive] = useState(false); const [isLoading, setIsLoading] = useState(false); const fetchData = async (url, method, body = null) => { setIsLoading(true); try { const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: body ? JSON.stringify(body) : null, }); if (!response.ok) { throw new Error(`Failed to ${method} data`); } const data = await response.json(); return method === 'GET' ? data.isActive : null; // Assuming 'isActive' property } catch (error) { console.error(`Error ${method}ing data:`, error); } finally { setIsLoading(false); } }; useEffect(() => { fetchData('your-api-endpoint', 'GET') .then(data => setIsActive(data)) // Set initial state .catch(error => console.error(error)); }, []); const toggleActive = async () => { const updatedActive = !isActive; await fetchData('your-api-endpoint', 'POST', { isActive: updatedActive }); setIsActive(updatedActive); }; return ( <button className={`${styles.button} ${isActive ? styles.active : styles.inactive}`} disabled={isLoading} onClick={toggleActive} > {/* ... rest of the component JSX ... */} </button> ); }; export default ButtonComponent;
What are keys in react?
A “key” is a special string attribute you need to include when creating lists of elements in React. Keys are used in React to identify which items in the list are changed, updated, or deleted.
Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.
Disadvantages of real DOM :
Every time the DOM gets updated, the updated element and its children have to be rendered again to update the UI of our page. For this, each time there is a component update, the DOM needs to be updated and the UI components have to be re-rendered.
Example:
React JS Refs
Refs are a function provided by React to access the DOM element and the React elements created in components. They are used in cases where we want to change the value of a child component, without making use of props and state.
How does virtual DOM actually make things faster?
When anything new is added to the application, a virtual DOM is created and it is represented as a tree. Each element in the application is a node in this tree. So, whenever there is a change in the state of any element, a new Virtual DOM tree is created. This new Virtual DOM tree is then compared with the previous Virtual DOM tree and make a note of the changes. After this, it finds the best possible ways to make these changes to the real DOM. Now only the updated elements will get rendered on the page again.
Controled components
Controlled Components
In simple HTML elements like input tags, the value of the input field is changed whenever the user type. But, In React, whatever the value the user types we save it in state and pass the same value to the input tag as its value, so here DOM does not change its value, it is controlled by react state. These are known as Controlled Components.
What are react hooks?
Hooks are reusable functions that provide access to state in React Applications. Hooks give access to states for functional components while creating a React application. It allows you to use state and other React features without writing a class
Use Context ?
Usually, you will pass information from a parent component to a child component via props. But passing props can become verbose and inconvenient if you have to pass them through many components in the middle, or if many components in your app need the same information. Context lets the parent component make some information available to any component in the tree below it—no matter how deep—without passing it explicitly through props.
global data -> current authenticated user or theme(e.g. color, paddings, margins, font-sizes).
The Context API allows for more flexibility in how state is managed and accessed compared to Redux, which follows a more structured pattern with actions, reducers, and a single store.
Context lets a component provide some information to the entire tree below it.
To pass context:
Create and export it with export const MyContext = createContext(defaultValue).
Pass it to the useContext(MyContext) Hook to read it in any child component, no matter how deep.
Wrap children into <MyContext.Provider value={…}> to provide it from a parent.
Context passes through any components in the middle.
Context lets you write components that “adapt to their surroundings”.
Before you use context, try passing props or passing JSX as children.
useState Hook
The useState Hook provides those two things:
A state variable to retain the data between renders.
A state setter function to update the variable and trigger React to render the component again.
When you call useState, you are telling React that you want this component to remember something:
const [index, setIndex] = useState(0);
In this case, you want React to remember index.
The convention is to name this pair like const [something, setSomething].
The only argument to useState is the initial value of your state variable
Every time your component renders, useState gives you an array containing two values:
The state variable (index) with the value you stored.
The state setter function (setIndex) which can update the state variable and trigger React to render the component again.
What is useEffect hook in React?
Some components need to stay connected to the network, some browser API, or a third-party library, while they are displayed on the page. These systems aren’t controlled by React, so they are called external.
To connect your component to some external system, call useEffect at the top level of your component:
The useEffect in ReactJS is used to handle the side effects such as fetching data and updating DOM. This hook runs on every render but there is also a way of using a dependency array using which we can control the effect of rendering
So run on update of var in the dependancy [test]
Once when dependacy is []
and on every render wheren there is no dependacy array so if you set state in useEffect and dont have dependancy array you have an infinite loop
How does it useEffect work?
You call useEffect with a callback function that contains the side effect logic.
By default, this function runs after every render of the component.
You can optionally provide a dependency array as the second argument.
The effect will only run again if any of the values in the dependency array change.
Controlling side effects in useEffect :
1. To run useEffect on every render do not pass any dependency
useEffect(()->{
// Example Code
})
- To run useEffect only once on the first render pass any empty array in the dependecy
useEffect(()->{
// Example Code
}, [] )
- To run useEffect on change of a particular value. Pass the state and props in the dependency array
Syntax Parser, Execution Context, and Lexical Environment
Syntax parser - a program that reads your code and determines what it does and if its grammar/syntax is valid.
When you write JavaScript it isn’t directly telling computer what to do. You’re writing code, but then someone else built programs that convert your JS into something that computer can understand. Those programs are called compilers or interpreters.
Compilers go character by character and translate your code into a set of instructions. Important to understand is that during that process programmers who wrote that compiler can choose to do extra stuff. Your code is not what actually is given to a computer but a translation of it.
Lexical environment - where something sits physically in the code you write and what surrounds it. In JavaScript where you write something is important.
Execution context - a wrapper to help manage the code that is running. There are lots of lexical environments, areas of the code that you look at physically, but which one is currently running is managed via execution contexts. Execution context contains your running code, but it can also contain things beyond what you’ve written in your code. Because remember that your code is being translated by a syntax parser.
The Scope Chain
If JavaScript engine doesn’t find variable in it’s own environment it looks in the outer environment. That whole process of searching of variable in outer lexical environments down the chain is called the scope chain.
Hoisting
Hoisting - because of the way JS works, you can write in your code a call to a function before an actual function and it will execute without any errors.
b();
function b() {
console.log(‘This works!’);
}
let avoids Hoisting
Asynchronous Callbacks
Asynchronous - executed more than one at a time. What is happening inside JS engine is synchronous. Its just the browser is putting things asynchronously in the event queue.
Event queue - events like click and others are placed in the queue. And this queue starts to get processed in the order it happened only when execution stack is empty.
Conceptual Aside Coercion
Coercion - converting a value from one type to another. This happens quite often in JavaScript because it’s dynamically typed. For example adding a number to a string would result in number being converted to a string:
7 + ‘7’// would be = ‘77’
Immediately Invoked Functions Expressions (IIFEs)
Using an Immediately Invoked Function Expression (IIFE):
var firstname = ‘John’;
(function(name) {
var greeting = 'Inside IIFE: Hello'; console.log(greeting + ' ' + name);
}(firstname)); // IIFE
Framework Aside IIFEs and Safe Code
IIFE creates a new execution context so it’s safe code because it is wrapped in separate execution context and prevents variable names collision. Wrapping code libraries is very common pattern to not clash code with the global object. You can reference to global object by passing window as a parameter.
Understanding Closures
When a function runs and completes it is removed from execution stack, but variables created and saved in that execution phase are still stored in memory and can be accessed from down the scope.
function greet(whattosay) { return function(name) { console.log(whattosay + ' ' + name; } } var sayHi = greet('Hi'); sayHi('Jason');
Inside the variable sayHi we run greet function which returns another function and passes string ‘Hi’. After that functions is finished and it is popped from the execution stack. But whattosay variable still sits saved in the memory with a value Hi. So when we call function sayHi it will go in the outer environment and look for whattosay variable and will find it and log “Hi Jason”. We describe this proccess as execution context has closed in outer variables.
Closures And Callbacks
Callback function - a function you give to another function to be run when the other function is finished.
Describe the key differences between state and props in React
In React, both state and props are used to pass data, but they serve different purposes. State is mutable and managed within a component, while props are immutable and passed down from a parent component.
Explain the concept of a closure in JavaScript.
A closure is created when a function is defined inside another function, allowing the inner function to access variables from the outer (enclosing) function even after the outer function has finished executing. Closures are a powerful mechanism for data encapsulation and maintaining the state.
Explain the concept of components in React.
Components are the building blocks of a React application, encapsulating both the UI and behavior of a specific part of the application. They promote reusability and modularity by allowing developers to compose complex interfaces from smaller, self-contained units.
How do you ensure accessibility in your frontend applications?
To ensure accessibility, I follow the Web Content Accessibility Guidelines (WCAG), use semantic HTML elements, add appropriate ARIA attributes, ensure proper contrast ratios, and test my applications using screen readers and other assistive technologies
Can you explain the concept of web components and their benefits?
Web components are a set of web platform APIs that enable developers to create custom, reusable HTML elements. They promote modularity, encapsulation, and interoperability, allowing for more maintainable and scalable frontend applications.
What is the role of design systems in frontend development?
Design systems provide a collection of reusable components, guidelines, and principles that help ensure a consistent user experience and visual language across applications. They promote efficiency, collaboration, and maintainability in frontend development.
How do you handle internationalization (i18n) and localization (l10n) in frontend applications
I handle internationalization and localization by using libraries like i18next or react-intl to manage translations and formatting. These libraries provide a mechanism for storing and retrieving translated strings, as well as handling date, time, and number formatting based on the user’s locale.
Can you explain the concept of event delegation in JavaScript?
Event delegation is a technique that involves binding an event listener to a parent element instead of individual child elements. When an event occurs on a child element, it bubbles up to the parent, which then handles the event. This technique can improve performance and memory usage by reducing the number of event listeners and simplifying event management.
Can you explain the role of custom elements in frontend development?
Custom elements are part of the web components standard that allows developers to define and create reusable, encapsulated HTML elements with custom behavior and styling. They promote modularity and interoperability in frontend applications, making it easier to build and maintain complex UI components.
Can you explain the role of the Shadow DOM in frontend development?
The Shadow DOM is a part of the Web Components standard that provides encapsulation for DOM elements and their styles, keeping them separate from the main document tree. It enables the creation of reusable and self-contained components that don’t interfere with other parts of the application. The Shadow DOM promotes modularity and maintainability in frontend development by preventing global style and DOM conflicts.
What’s the difference between a Callback and a Promise?
Calback
A function passed as an argument to another function and executed later -> useEffect
Promise
An object representing a future value of an asynchronous operation
Single .catch() to handle errors in the chain
Has pending, fulfilled, and rejected states
What do you think will become the next big trend in web development?
What are the React lifecycle methods?
function MyComponent() {
useEffect(() => {
// componentDidMount logic here
// componentDidUpdate logic here for dependency changes
return () => { // componentWillUnmount logic here }; }, []); // Dependency array makes this behave like componentDidMount and componentWillUnmount }
Mutatate inmutabale data why whaty
In React, immutability means creating new copies of state rather than modifying the original data. This is crucial because React relies on reference changes to detect updates and re-render components. If data is mutated directly, React may miss changes, leading to unexpected behavior.
For example:
To add an item to an array: setItems([…items, newItem]) instead of items.push(newItem).
To update an object: setUser({ …user, age: 26 }) instead of user.age = 26.
Immutability makes state changes predictable and helps React perform efficiently.
Example of useCallback real word example in react?
What is useCallback and what is useMemo diference and example
What is jsx?
What is React?
React is a JavaScript library for building user interfaces. It allows developers to create reusable components and efficiently update the UI using a virtual DOM.
Declarative → You describe what UI should look like, React updates it.
Component-Based → Apps are broken down into independent, reusable pieces.
State Management → Uses useState, useReducer, or external libraries like Zustand or Redux.
Unidirectional Data Flow → Props pass data from parent to child components.
🔹 What You Write vs. What You See in the Browser
You Write (JSX in React)
jsx```
function App() {
return <h1>Hello, world!</h1>;
}
What React Compiles It Into (JavaScript)
js
React.createElement(“h1”, null, “Hello, world!”);
What the Browser Sees (HTML Output)
html
<h1>Hello, world!</h1>
React transforms JSX into JavaScript, then updates the actual DOM based on changes.
Promise, async await. asyncronios request history explanation?
what’s the diference between them what are they ?
How does react work ? How is it built how do you render it in the browser how works under the hood?
Most common patterns in front end development ?
How next js works ? what’s the difrenece between it and react?
Best Practices for Testing in React?
Write unit tests for simple, isolated logic (e.g., functions or standalone components). - Jest: A JavaScript testing framework ,
React Testing Library: This library is built on top of Jest and provides utilities to render components and query
Use integration tests for components that interact with each other or that depend on context or state. - Cypress: This end-to-end testing tool
Avoid testing implementation details (like class names or internal states) and focus on user interactions and output.
jQuery and JavaScript/ES6
diferences what is each how are they related to each other why jQuery went away?
- What is JavaScript/ES6?
JavaScript is a core, versatile programming language native to the web. It allows developers to add interactivity, animations, and control over webpage content and behavior.
ES6 (ECMAScript 2015) is a major update to JavaScript that introduced new features, syntax improvements, and functionality to make the language more powerful and concise.
Examples include arrow functions, classes, template literals, let and const, Promise objects, and async functions.
- What is jQuery?
jQuery is a JavaScript library released in 2006 that simplifies HTML document traversal, manipulation, event handling, and animation. It was created to address cross-browser compatibility issues and to make JavaScript more accessible for common tasks with a simplified, unified syntax.
Arrow functions vs normal functions
this Binding: Arrow functions don’t have their own this context; instead, they inherit this from the surrounding (lexical) scope.
preserve the this context from the outer scope.
This is useful in cases like callbacks within a method where you want to maintain the class’s this.
Implicit Return: If an arrow function has only one expression, it can implicitly return the value of that expression without needing the return keyword.
// Regular function in a method
function Person() {
this.name = “Alice”;
setTimeout(function() {
console.log(this.name); // undefined, because this
refers to the global context
}, 1000);
}
// Using an arrow function
function Person() {
this.name = “Alice”;
setTimeout(() => {
console.log(this.name); // Alice, because this
refers to the Person
instance
}, 1000);
}
Classes in javascript
Classes are a syntactical sugar over JavaScript’s existing prototype-based inheritance. They make it easier to create and understand object-oriented code.
Key Features:
Constructor: The constructor method is used to initialize an object created with the class.
Inheritance: Classes support inheritance with the extends keyword, allowing one class to inherit properties and methods from another.
Static Methods: Classes can have static methods that are called on the class itself, not on instances.
// ES5 Constructor function
function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function() {
console.log(${this.name} makes a noise.
);
};
// ES6 Class
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(${this.name} makes a noise.
);
}
}
const dog = new Animal(“Dog”);
dog.speak(); // Dog makes a noise.
ES6 - Template Literals
Template literals are a way to embed variables and expressions directly within strings using backticks (`) and ${} syntax. They make string concatenation and multi-line strings more readable and manageable.
Typescript
Enums define named constants, making code more readable and easier to work with than using plain constants.
enum Direction {
Up,
Down,
Left,
Right,
}
let move: Direction = Direction.Up;
Intersection Type Example:
interface Person {
name: string;
}
interface Employee {
employeeId: number;
}
type Staff = Person & Employee;
const staff: Staff = { name: “Alice”, employeeId: 101 };
Union Type Example:
function format(input: string | number) {
return input.toString();
}
Interfaces and type aliases allow you to define custom types and create complex type structures, making code more readable and manageable.
interface User {
name: string;
age: number;
isAdmin: boolean;
}
const user: User = { name: “Alice”, age: 30, isAdmin: false };
Utility Types
const user: Partial<User> = {}; // All properties are optional now</User>
What is the difference between var, let, and const?
var: Function-scoped, hoisted, can be redeclared.
let: Block-scoped, not hoisted, cannot be redeclared.
const: Block-scoped, immutable reference (but object properties can change).
What are closures, and how do they work?
A closure is a function that retains access to variables from its parent scope, even after the parent function has executed. Useful for encapsulation and data privacy.
How does the React Virtual DOM work?
React creates a lightweight copy of the DOM, compares changes (diffing), and efficiently updates only the parts that changed, improving performance.
What is the difference between React hooks and class components?
Hooks (useState, useEffect, etc.) allow functional components to manage state and side effects without needing class components. They simplify code and improve reusability.
How is state managed in React?
Small apps: useState, useContext.
Medium apps: Zustand, Jotai.
Large apps: Redux, Recoil (for complex global state).
How can you optimize a React application?
Use useMemo and useCallback to prevent unnecessary re-renders.
Implement lazy loading and code splitting.
Optimize images and assets using WebP, SVGs.
What are the differences between useEffect, useMemo, and useCallback?
useEffect: Runs side effects after rendering.
useMemo: Caches expensive calculations to avoid re-computation.
useCallback: Memoizes functions to prevent unnecessary re-creation.
How do you handle responsiveness in CSS?
Use Flexbox, CSS Grid, media queries, and frameworks like Tailwind CSS.
Apply a mobile-first approach and use rem/em units instead of px.
What is the difference between CSS Grid and Flexbox?
Grid: Best for 2D layouts (rows & columns).
Flexbox: Best for 1D layouts (row OR column).
What are CSS preprocessors?
SASS/LESS for nesting, variables, mixins, and better maintainability.
How do you optimize large apps?
Use lazy loading, SSR (Next.js), and tree shaking.
Optimize API calls with debouncing, throttling, and caching.
Minify CSS, JS, and optimize image assets.
What is the difference between lazy loading and code splitting?
Lazy loading: Loads components only when needed (React.lazy()).
Code splitting: Breaks app into smaller chunks for better performance (webpack splitChunks, automated in next, all pages are split in it’s own chunk so we don’t load everything at once).
Use Lazy Loading when:
You have a large component that isn’t immediately visible (e.g., modals, carousels, heavy charts).
You need to load a browser-only dependency that doesn’t work with SSR (ssr: false).
You want to reduce time-to-interactive (TTI).
✅ Use Code Splitting when:
You want to break large bundles into smaller chunks.
You want to avoid unnecessary JavaScript downloads for unused components.
You’re using Next.js pages (which automatically do code splitting).
What is the difference between debouncing and throttling?
Debouncing: Delays execution until user stops an action (e.g., search input).
Throttling: Limits execution to once per interval (e.g., scroll event).
Execution delay:
Debounce: Yes, waits until user stops
Throttling: No, runs at fixed intervals
Use case
Debounce: Search input, text input validation Scroll, resize, drag events
Example
Debounce: API call after user stops typing
Throttling: Running an event handler every 500ms
How do you structure a large frontend project?
Use a modular structure (components/, hooks/, api/, contexts/, utils).
Keep UI and business logic separate for maintainability.
create custom hooks for API calls instead of keep it in the component separate business from UI
Use feature-based folders if the project scales.
src/
├── features/
│ ├── weather/
│ │ ├── components/
│ │ │ ├── WeatherWidget.tsx
│ │ │ ├── TemperatureDisplay.tsx
│ │ ├── hooks/
│ │ │ ├── useWeather.ts
│ │ ├── api/
│ │ │ ├── weatherAPI.ts
│ │ ├── Weather.module.css
│ │ ├── index.ts
│ ├── auth/
│ │ ├── components/
│ │ │ ├── Login.tsx
│ │ ├── hooks/
│ │ │ ├── useAuth.ts
│ │ ├── api/
│ │ │ ├── authAPI.ts
│ │ ├── index.ts
├── shared/
│ ├── components/
│ │ ├── Button.tsx
│ │ ├── Modal.tsx
│ ├── utils/
│ │ ├── formatDate.ts
│ │ ├── debounce.ts
│ ├── styles/
│ │ ├── global.css
├── App.tsx
├── main.tsx
How do you manage a growing component library?
Use Storybook for component documentation.
Create reusable UI components with prop-driven designs.
Prop Driven design:
A button should render only the types of UI buttons that exist no need to create any useState in it that should be handled in the parent like a counter or anything else
What are the pros and cons of micro-frontends?
Pros: Scales across teams, independent deployments.
Cons: Harder state management, increased complexity.
How do you design a real-time, high-performance UI?
Use WebSockets for real-time data.
Optimize re-renders with useMemo and React.memo().
Use virtualized lists for rendering large datasets.
What is the difference between REST and GraphQL?
REST: Fixed endpoints, over-fetching possible.
GraphQL: Flexible queries, reduces over-fetching, but requires additional complexity on the backend.
How do you handle API errors and loading states?
Use error boundaries in React.
Centralize API calls in a custom hook (useFetch).
Show proper loading and error UI (Suspense, spinners, skeletons).
How do you secure API calls?
Use HTTPS, authentication tokens (JWT/OAuth).
Validate user input before sending requests.
What is your testing approach?
Unit tests (components, functions) → Vitest + React Testing Library.
Integration tests (API + UI together).
E2E tests → Cypress.
How do you write unit tests in React?
import { render, screen } from “@testing-library/react”;
import Button from “./Button”;
test(“renders the button correctly”, () => {
render(<button></button>);
expect(screen.getByText(“Click me”)).toBeInTheDocument();
});
What is the difference between unit, integration, and E2E tests?
Unit: Tests individual components.
Integration: Tests how components interact (e.g., API + UI).
E2E: Tests the full user flow (e.g., login, checkout).
What is your experience with Cypress for UI testing?
Yes, I write E2E tests to simulate real user interactions.
Example:
describe(“Login Flow”, () => {
it(“logs in successfully”, () => {
cy.visit(“/login”);
cy.get(“#username”).type(“user123”);
cy.get(“#password”).type(“password123”);
cy.get(“button”).click();
cy.url().should(“include”, “/dashboard”);
});
});
What makes you a great fit for this role?
Strong Frontend Expertise: Deep knowledge of React, JavaScript, performance optimization, and modern UI architectures.
Scalability & Maintainability: Experienced in structuring large-scale frontend projects with clean architecture and reusable components.
API & Backend Integration: Proficient in REST, GraphQL, error handling, and securing API calls.
Testing & Code Quality: Strong background in TDD, unit, integration, and E2E testing using Vitest, Cypress, and React Testing Library.
Collaborative Mindset: I enjoy working with UX/UI designers, backend developers, and product teams to create polished and scalable applications.
What are closures, and how do they work?
A closure is a function that retains access to variables from its parent scope, even after the parent function has executed. Useful for encapsulation and data privacy.
How does the React Virtual DOM work?
React creates a lightweight copy of the DOM, compares changes (diffing), and efficiently updates only the parts that changed, improving performance.
React hooks vs. class components?
Hooks allow functional components to manage state and side effects without needing class components. They simplify code and improve reusability.
State management in React?
Small apps: useState, useContext. Medium apps: Zustand, Jotai. Large apps: Redux, Recoil.
Optimizing a React application?
Use useMemo and useCallback to prevent unnecessary re-renders. Implement lazy loading and code splitting. Optimize images and assets using WebP, SVGs.
Differences: useEffect, useMemo, useCallback?
useEffect: Runs side effects after rendering.
useMemo: Caches expensive calculations.
useCallback: Memoizes functions to prevent unnecessary re-creation.
Premature, unscientific optimization is a waste of time, and potentially harmful.
premature = before it’s proven you need it. Do you have a slow screen or application? No? Then no need to optimize performance. Optimize readability over everything instead.
unscientific = you haven’t measured anything. Every scenario is different, you should measure a “before” performance metric, make your change, measure an “after”. You will be surprised very often what doesn’t help, and what can be actively harmful.
useMemo
Computations that don’t need to run on every render (e.g., filtering, sorting, calculations, dont change on every render based on the dependencies array vallue) it’s basically caching get the first value and use it until the dependencies array value changes
useCallback
Functions passed to child components to avoid unnecessary re-renders
CSS Grid vs. Flexbox?
Grid: Best for 2D layouts (rows & columns). Flexbox: Best for 1D layouts (row OR column).
CSS Preprocessors?
SASS/LESS for nesting, variables, mixins, and better maintainability.
Optimizing large apps?
Use lazy loading, SSR (Next.js), and tree shaking. Optimize API calls with debouncing, throttling, and caching. Minify CSS, JS, and optimize image assets.
Lazy loading vs. code splitting?
Lazy loading: Loads components only when needed (React.lazy()).
Code splitting: Breaks app into smaller chunks for better performance (webpack splitChunks).
Debouncing vs. Throttling?
Debouncing: Delays execution until user stops an action (e.g., search input). Throttling: Limits execution to once per interval (e.g., scroll event).
Structuring a large frontend project?
Use a modular structure (components/, hooks/, services/, contexts/). Keep UI and business logic separate. Use feature-based folders if the project scales.
Managing a growing component library?
Use Storybook for component documentation. Create reusable UI components with prop-driven designs.
Micro-frontends: pros/cons?
Pros: Scales across teams, independent deployments. Cons: Harder state management, increased complexity.
Designing a real-time, high-performance UI?
Use WebSockets for real-time data. Optimize re-renders with useMemo and React.memo(). Use virtualized lists for rendering large datasets.
REST vs. GraphQL?
REST: Fixed endpoints, over-fetching possible. GraphQL: Flexible queries, reduces over-fetching, but requires additional complexity on the backend.
Handling API errors and loading states?
Use error boundaries in React. Centralize API calls in a custom hook (useFetch). Show proper loading and error UI (Suspense, spinners, skeletons).
Optimistic UI updates?
Assume success before the server confirms and update the UI instantly. Rollback changes if API fails (e.g., like buttons on social media).
Securing API calls?
Use HTTPS, authentication tokens (JWT/OAuth). Validate user input before sending requests.
Testing approach?
Unit tests (components, functions) → Vitest + React Testing Library. Integration tests (API + UI together). E2E tests → Cypress.
Writing unit tests in React?
import { render, screen } from ‘@testing-library/react’; import Button from ‘./Button’; test(‘renders the button correctly’, () => { render(<button></button>); expect(screen.getByText(‘Click me’)).toBeInTheDocument(); });
Unit vs. integration vs. E2E tests?
Unit: Tests individual components. Integration: Tests how components interact (e.g., API + UI). E2E: Tests the full user flow (e.g., login, checkout).
Experience with Cypress for UI testing?
Yes, I write E2E tests to simulate real user interactions. Example: describe(‘Login Flow’, () => { it(‘logs in successfully’, () => { cy.visit(‘/login’); cy.get(‘#username’).type(‘user123’); cy.get(‘#password’).type(‘password123’); cy.get(‘button’).click(); cy.url().should(‘include’, ‘/dashboard’); }); });
Strong Frontend Expertise
Deep knowledge of React, JavaScript, performance optimization, and modern UI architectures.
Scalability & Maintainability
Experienced in structuring large-scale frontend projects with clean architecture and reusable components.
API & Backend Integration
Proficient in REST, GraphQL, error handling, and securing API calls.
Testing & Code Quality
Strong background in TDD, unit, integration, and E2E testing using Vitest, Cypress, and React Testing Library.
Collaborative Mindset
I enjoy working with UX/UI designers, backend developers, and product teams to create polished and scalable applications.