
ReactJS is a leading library for building dynamic and responsive user interfaces, making it an essential skill for frontend and full-stack developers. Stark.ai offers curated ReactJS interview questions, hands-on challenges, and expert insights to help you stand out in your next interview.
React is a JavaScript library for building user interfaces, particularly single-page applications. It allows...
Components are the building blocks of a React application. They are reusable, independent pieces of UI that can be...
JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows you to write HTML elements in...
The virtual DOM is a lightweight copy of the real DOM that React uses to track changes. React updates the virtual...
JSX is a syntax extension for JavaScript that allows writing HTML-like code in React. Unlike HTML, JSX uses...
Functional components are JavaScript functions that accept props and return JSX, making them simpler and more...
Props are passed as attributes in JSX, similar to HTML attributes. Parent components can pass any JavaScript value...
JSX supports conditional rendering through: 1) Ternary operators {condition ? elementA : elementB}, 2) Logical &&...
Dynamic attributes in JSX use curly braces to embed JavaScript expressions: className={`base ${conditional}`},...
Lists are rendered using array methods like map(). Each list item must have a unique 'key' prop for React's...
Default exports (export default Component) allow importing with any name but limit one per file. Named exports...
Inline styles in JSX use double curly braces and camelCase properties: style={{backgroundColor: 'blue'}}. Values can...
Conditional CSS classes can be handled using template literals, array join methods, or className utilities like...
useState is a React hook that adds state to functional components. It returns an array with the current state value...
Always treat state as immutable. Use spread operator or Object.assign() for objects: setState({...state, newProp:...
Local state (useState, useReducer) is component-specific and used for UI state. Global state (Context, Redux) is...
The three main phases are: Mounting (component is created and inserted into DOM), Updating (component re-renders due...
useEffect combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount. The effect...
componentDidMount executes after the component mounts to the DOM. It's used for initial setup like API calls,...
componentWillUnmount handles cleanup before component removal. In hooks, return a cleanup function from useEffect to...
Constructor initializes state and binds methods in class components. In functional components, useState and...
The Rules of Hooks are: 1) Only call hooks at the top level (not inside loops, conditions, or nested functions), 2)...
Custom hooks are functions that use other hooks and must start with 'use' (e.g., useCustomHook). They allow you to...
Props (properties) are read-only data passed from parent to child components. They enable unidirectional data flow,...
In functional components, use default parameters: function Component({prop = defaultValue}). In class components,...
children is a special prop that contains the content between component tags. It enables component composition:...
Use descriptive names, follow consistent conventions, group related props, document prop types and requirements....
Use props in conditional statements, ternary operators, or logical && operator. Handle loading/error states....
Synthetic events are React's cross-browser wrapper around native DOM events. They provide consistent behavior across...
Methods include: arrow functions in render, class fields with arrow functions, binding in constructor, or using...
Form events (onChange, onSubmit) are handled using controlled components where form data is controlled by React...
A controlled component is one where form data is controlled by React state. Every state change goes through...
Use state to store input value and onChange handler to update it: const [value, setValue] = useState(''); return...
React Router is a standard routing library for React that enables navigation between views in a React application....
BrowserRouter uses HTML5 history API and creates clean URLs (/about), while HashRouter uses URL hash (/#/about)....
Switch renders the first Route or Redirect that matches the current location exclusively. It prevents multiple...
Use Route path with parameter syntax (:param), access parameters via useParams hook or match.params. Example: <Route...
Create a catch-all route at the end of Switch using path='*' or no path prop. Render a 404 component for unmatched...
exact ensures the path matches exactly the current URL. Without exact, '/users' would match '/users/new'. Use for...
NavLink is a special version of Link that can be styled when it matches the current URL. Useful for navigation menus...
Relative links are paths relative to the current route. Use them for nested navigation and maintaining route...
React.memo() is a higher-order component that memoizes component renders based on prop changes. Use it to prevent...
Use React.memo for functional components, PureComponent for class components, implement shouldComponentUpdate...
Keys help React identify which items have changed, been added, or removed in lists. Proper key usage optimizes...
Keys enable efficient list updates by helping React identify changed items. Use stable, unique identifiers as keys,...
Context API provides a way to pass data through the component tree without having to pass props manually at every...
The core components are: React.createContext() to create a context, Context.Provider to wrap components that need...
Create context using React.createContext(defaultValue) and provide it using the Provider component:...
Default value is used when a component consumes context but isn't wrapped in a provider. It's useful for testing,...
Context complements props by providing a way to share values without explicit passing. Use context for truly global...
Use clear naming conventions, organize contexts by feature/domain, implement proper file structure. Consider...
Error Boundaries are React components that catch JavaScript errors in their child component tree and display...
Use try-catch blocks in event handlers, implement proper error handling and state updates, provide user feedback....
Provide clear, actionable error messages, implement proper i18n, consider user experience, maintain consistency....
Main testing libraries include Jest (test runner and assertion library), React Testing Library (component testing),...
React Testing Library is a testing utility that encourages testing components as users would use them. It focuses on...
Shallow rendering tests component in isolation without rendering child components, while mount rendering fully...
Group related tests, maintain clear test structure, use proper naming conventions. Consider test maintainability and...
Main approaches include: CSS Modules, Styled Components, CSS-in-JS libraries, traditional CSS/SASS, Tailwind CSS,...
CSS Modules are CSS files where all class names are scoped locally by default. They solve naming conflicts, provide...
Styled Components is a CSS-in-JS library that allows writing actual CSS in JavaScript. Components are created with...
Use template literals, classnames library, CSS modules composition, or styled-components props. Handle dynamic...
Key principles include: single responsibility, reusability, proper prop drilling avoidance, composition over...
Use prop types or TypeScript, implement proper prop validation, avoid excessive props, use proper prop naming, and...
Implement proper JSDoc comments, maintain clear prop documentation, document component usage, provide examples, and...
Common methods include fetch API, Axios, React Query, SWR, GraphQL clients. Each has different features for handling...
Use useEffect for API calls, handle cleanup with cancel tokens, manage loading and error states, implement proper...
React is a JavaScript library for building user interfaces, particularly single-page applications. It allows developers to create reusable UI components and manage the application's state efficiently.
Components are the building blocks of a React application. They are reusable, independent pieces of UI that can be written as functions or classes, and they accept props as input to produce rendered HTML.
JSX (JavaScript XML) is a syntax extension for JavaScript used in React. It allows you to write HTML elements in JavaScript and place them in the DOM without using `createElement()` or `appendChild()`.
The virtual DOM is a lightweight copy of the real DOM that React uses to track changes. React updates the virtual DOM first and then efficiently updates the real DOM, minimizing direct manipulation and improving performance.
JSX is a syntax extension for JavaScript that allows writing HTML-like code in React. Unlike HTML, JSX uses camelCase properties, requires closing all tags, uses className instead of class, and can directly embed JavaScript expressions using curly braces {}.
Functional components are JavaScript functions that accept props and return JSX, making them simpler and more concise. Class components extend React.Component, can have local state and lifecycle methods, but are generally more verbose. Modern React primarily uses functional components with hooks.
Props are passed as attributes in JSX, similar to HTML attributes. Parent components can pass any JavaScript value (strings, numbers, objects, functions) to child components. Child components receive these props as function parameters or this.props in class components.
JSX supports conditional rendering through: 1) Ternary operators {condition ? elementA : elementB}, 2) Logical && operator for simple conditions {condition && element}, 3) If statements outside the return statement, 4) Extracting conditions to separate methods.
Dynamic attributes in JSX use curly braces to embed JavaScript expressions: className={`base ${conditional}`}, style={{property: value}}, or data-attributes={dynamicValue}. Boolean attributes can be set using conditional expressions.
Lists are rendered using array methods like map(). Each list item must have a unique 'key' prop for React's reconciliation process. Keys should be stable, predictable, and unique among siblings. Using array indices as keys is generally discouraged except for static lists.
Default exports (export default Component) allow importing with any name but limit one per file. Named exports (export const Component) require exact names or aliases when importing but allow multiple exports per file. Choice affects module organization and refactoring.
Inline styles in JSX use double curly braces and camelCase properties: style={{backgroundColor: 'blue'}}. Values can be strings or numbers (pixels automatically added). Dynamic styles can use expressions or computed properties.
Conditional CSS classes can be handled using template literals, array join methods, or className utilities like classnames library. Example: className={`base ${condition ? 'active' : ''}`} or using object syntax with classnames.
useState is a React hook that adds state to functional components. It returns an array with the current state value and a setter function: const [state, setState] = useState(initialValue). The setter function triggers re-renders when called to update state.
Always treat state as immutable. Use spread operator or Object.assign() for objects: setState({...state, newProp: value}). For arrays, use methods like map, filter, or spread: setState([...items, newItem]). Never mutate state directly.
Local state (useState, useReducer) is component-specific and used for UI state. Global state (Context, Redux) is application-wide and used for shared data. Choose based on state scope and component coupling needs.
The three main phases are: Mounting (component is created and inserted into DOM), Updating (component re-renders due to prop or state changes), and Unmounting (component is removed from DOM). Each phase has associated lifecycle methods or hooks.
useEffect combines the functionality of componentDidMount, componentDidUpdate, and componentWillUnmount. The effect runs after render, and its cleanup function (if returned) runs before unmount and before re-running the effect.
componentDidMount executes after the component mounts to the DOM. It's used for initial setup like API calls, subscriptions, or DOM manipulations. In hooks, this is achieved using useEffect with an empty dependency array: useEffect(() => {}, []).
componentWillUnmount handles cleanup before component removal. In hooks, return a cleanup function from useEffect to achieve the same. Use it to remove event listeners, cancel subscriptions, and clear timers to prevent memory leaks.
Constructor initializes state and binds methods in class components. In functional components, useState and useCallback replace these roles. Initial state can be set directly with useState, and function definitions handle method binding.
The Rules of Hooks are: 1) Only call hooks at the top level (not inside loops, conditions, or nested functions), 2) Only call hooks from React function components or custom hooks. These rules ensure hooks maintain their state and order between renders.
Custom hooks are functions that use other hooks and must start with 'use' (e.g., useCustomHook). They allow you to extract component logic into reusable functions. Custom hooks can return any values and should follow the Rules of Hooks.
Props (properties) are read-only data passed from parent to child components. They enable unidirectional data flow, making the application's data flow predictable and easier to debug. Props can include any JavaScript value including functions.
In functional components, use default parameters: function Component({prop = defaultValue}). In class components, use static defaultProps property. Default props ensure components work even when optional props aren't provided.
children is a special prop that contains the content between component tags. It enables component composition: <Container>{content}</Container>. Can be manipulated using React.Children utilities and supports any valid JSX.
Use descriptive names, follow consistent conventions, group related props, document prop types and requirements. Consider prop grouping for complex components. Use spread operator judiciously.
Use props in conditional statements, ternary operators, or logical && operator. Handle loading/error states. Consider extract complex conditions to separate functions. Use proper TypeScript types.
Synthetic events are React's cross-browser wrapper around native DOM events. They provide consistent behavior across browsers, follow the W3C spec, and use a pooling mechanism for performance. Access native events via event.nativeEvent property.
Methods include: arrow functions in render, class fields with arrow functions, binding in constructor, or using function components with hooks. Each approach has performance and readability trade-offs. Example: onClick={() => this.handleClick()} or onClick={this.handleClick.bind(this)}.
Form events (onChange, onSubmit) are handled using controlled components where form data is controlled by React state. Prevent default form submission with e.preventDefault(). Handle validation and submission logic in event handlers.
A controlled component is one where form data is controlled by React state. Every state change goes through setState, making React the single source of truth. Uncontrolled components store form data in the DOM itself using refs. Controlled components provide more control but require more code.
Use state to store input value and onChange handler to update it: const [value, setValue] = useState(''); return <input value={value} onChange={e => setValue(e.target.value)} />. The component controls the input's value at all times.
React Router is a standard routing library for React that enables navigation between views in a React application. It provides components for handling routing declaratively, enabling the creation of single-page applications with multiple views and clean URLs.
BrowserRouter uses HTML5 history API and creates clean URLs (/about), while HashRouter uses URL hash (/#/about). BrowserRouter requires server configuration for direct URL access, while HashRouter works without it but has less clean URLs.
Switch renders the first Route or Redirect that matches the current location exclusively. It prevents multiple routes from rendering simultaneously and provides exclusive routing.
Use Route path with parameter syntax (:param), access parameters via useParams hook or match.params. Example: <Route path='/user/:id' /> and const { id } = useParams();
Create a catch-all route at the end of Switch using path='*' or no path prop. Render a 404 component for unmatched routes. Consider user experience and navigation options.
exact ensures the path matches exactly the current URL. Without exact, '/users' would match '/users/new'. Use for precise route matching and preventing partial matches.
NavLink is a special version of Link that can be styled when it matches the current URL. Useful for navigation menus and indicating active routes.
Relative links are paths relative to the current route. Use them for nested navigation and maintaining route hierarchy. Handle proper path resolution.
React.memo() is a higher-order component that memoizes component renders based on prop changes. Use it to prevent unnecessary re-renders of functional components when props haven't changed. Best for computationally expensive components.
Use React.memo for functional components, PureComponent for class components, implement shouldComponentUpdate correctly, and properly structure component hierarchy to minimize prop changes.
Keys help React identify which items have changed, been added, or removed in lists. Proper key usage optimizes reconciliation process and prevents unnecessary DOM operations. Use stable, unique identifiers.
Keys enable efficient list updates by helping React identify changed items. Use stable, unique identifiers as keys, avoid index as keys for dynamic lists, and ensure proper key propagation.
Context API provides a way to pass data through the component tree without having to pass props manually at every level. It solves prop drilling issues and enables global state management for specific data that needs to be accessed by many components.
The core components are: React.createContext() to create a context, Context.Provider to wrap components that need access to the context value, and Context.Consumer or useContext hook to consume the context value.
Create context using React.createContext(defaultValue) and provide it using the Provider component: <MyContext.Provider value={value}>{children}</MyContext.Provider>. The value prop can be any JavaScript value.
Default value is used when a component consumes context but isn't wrapped in a provider. It's useful for testing, default states, and fallback values. Should represent valid context state.
Context complements props by providing a way to share values without explicit passing. Use context for truly global state, props for component-specific data.
Use clear naming conventions, organize contexts by feature/domain, implement proper file structure. Consider maintainability and scalability.
Error Boundaries are React components that catch JavaScript errors in their child component tree and display fallback UI. They prevent the entire app from crashing and provide a way to gracefully handle runtime errors.
Use try-catch blocks in event handlers, implement proper error handling and state updates, provide user feedback. Consider global error handling for uncaught errors in events.
Provide clear, actionable error messages, implement proper i18n, consider user experience, maintain consistency. Handle different error types appropriately.
Main testing libraries include Jest (test runner and assertion library), React Testing Library (component testing), Enzyme (component testing), Cypress (E2E testing), and React Test Renderer (snapshot testing). Each serves different testing needs and approaches.
React Testing Library is a testing utility that encourages testing components as users would use them. It focuses on testing behavior rather than implementation details, promotes accessibility, and helps write more maintainable tests.
Shallow rendering tests component in isolation without rendering child components, while mount rendering fully renders component and children. Each has different use cases and performance implications.
Group related tests, maintain clear test structure, use proper naming conventions. Consider test maintainability and readability.
Main approaches include: CSS Modules, Styled Components, CSS-in-JS libraries, traditional CSS/SASS, Tailwind CSS, and inline styles. Each approach has different benefits for scoping, maintainability, and performance.
CSS Modules are CSS files where all class names are scoped locally by default. They solve naming conflicts, provide better encapsulation, and enable modular styling. Each component gets unique class names through compilation.
Styled Components is a CSS-in-JS library that allows writing actual CSS in JavaScript. Components are created with styles attached, supporting props-based styling, theming, and dynamic styles. Styles are scoped to components.
Use template literals, classnames library, CSS modules composition, or styled-components props. Handle dynamic classes and inline styles based on props or state.
Key principles include: single responsibility, reusability, proper prop drilling avoidance, composition over inheritance, and proper component hierarchy. Components should be small, focused, and maintainable.
Use prop types or TypeScript, implement proper prop validation, avoid excessive props, use proper prop naming, and consider prop drilling alternatives.
Implement proper JSDoc comments, maintain clear prop documentation, document component usage, provide examples, and consider documentation maintenance strategies.
Common methods include fetch API, Axios, React Query, SWR, GraphQL clients. Each has different features for handling requests, caching, error handling, and request cancellation.
Use useEffect for API calls, handle cleanup with cancel tokens, manage loading and error states, implement proper dependency array. Consider race conditions and component unmounting.
Be fluent in JSX, state management, and the component lifecycle.
Practice creating modular and reusable UI components.
Familiarize yourself with React hooks, Context API, and the latest React features.
Showcase personal or collaborative projects using ReactJS.
Join thousands of successful candidates preparing with Stark.ai. Start practicing ReactJS questions, mock interviews, and more to secure your dream role.
Start Preparing now