1. React is mainly used for developing ______.
React focuses on building interactive user interfaces for web and mobile apps. It doesn't handle databases or backend logic.
Get the Preplance app for a seamless learning experience. Practice offline, get daily streaks, and stay ahead with real-time interview updates.
Get it on
Google Play
4.9/5 Rating on Store
Meta · React
Practice React questions specifically asked in Meta interviews – ideal for online test preparation, technical rounds and final HR discussions.
Questions
110
Tagged for this company + subject
Company
Meta
View company-wise questions
Subject
React
Explore topic-wise practice
Go through each question and its explanation. Use this page for targeted revision just before your Meta React round.
React focuses on building interactive user interfaces for web and mobile apps. It doesn't handle databases or backend logic.
For complete preparation, combine this company + subject page with full company-wise practice and subject-wise practice. You can also explore other companies and topics from the links below.
Common Hooks include useState for state, useEffect for side effects, useRef for DOM refs, useContext for global context, useMemo and useCallback for optimization.
Every React class component must implement a render() method that returns the component’s UI.
You can style components using CSS modules, styled-components, inline styles, Tailwind, or plain CSS files. CSS modules and styled-components keep styles scoped.
React is fast thanks to Virtual DOM, SEO-friendly with server-side rendering, easy to learn, allows reusable components, and provides great developer tools. Its component model also promotes clean, maintainable code.
HOCs are wrapper functions that add logic or data to a component. They’re useful for features like authentication, theming, or analytics.
StrictMode is a tool that activates extra checks in development. It detects unsafe lifecycle methods, side-effect bugs, and deprecated APIs.
ReactDOM.render() mounts or updates React elements into the DOM. It connects your React app to a real HTML container, typically linking JavaScript logic to browser display.
ReactDOM.render(<App />, document.getElementById('root'));JSX stands for JavaScript XML. It allows developers to write HTML-like syntax inside JavaScript, making UI creation easier and more readable. React converts JSX into standard JavaScript using React.createElement() calls.
const element = <h1>Hello, React!</h1>;
// Compiles to: React.createElement('h1', null, 'Hello, React!');Props (short for properties) are inputs passed from parent to child components. They are read-only and used to send data or event handlers into components.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}In React, data flows in one direction — from parent to child through props. This predictable flow makes debugging and state management simpler.
React is a component-based JavaScript library for building reusable UI elements and handling user interface logic efficiently.
Prop drilling happens when you pass data through many nested components just to reach a deeply nested child. It can make code harder to maintain and understand.
Hooks cover most features like state and lifecycle methods, but error boundaries and getSnapshotBeforeUpdate still require classes.
There are three phases: mounting (render and init), updating (re-render on changes), and unmounting (cleanup). React handles each phase internally.
Use React.memo, useCallback, useMemo to avoid unnecessary renders. Code-split with React.lazy, lazy-load images, and virtualize long lists with react-window.
setState() schedules an update to the component’s state and re-renders it. It can also accept a callback that runs after the update is complete.
Props are used to pass data from parent components to child components. They make components reusable and customizable.
Hooks are special functions that let you use React features like state and lifecycle inside functional components. They were introduced to avoid complex class components and make logic reusable.
Group code by feature: `components/`, `pages/`, `hooks/`, `context/`, `services/`, and `assets/`. Keep reusable components separate and avoid deep nesting. Use index.js barrels for cleaner imports.
React component lifecycle includes three phases: Mounting (component created and added to DOM), Updating (re-render due to state/prop changes), and Unmounting (component removed from DOM). Hooks like useEffect can handle these phases in functional components.
Fragments let you group multiple elements without adding extra nodes to the DOM. They help keep your DOM clean and lightweight.
<> <h1>Title</h1> <p>Content</p> </>
Portals let you render components outside the main DOM hierarchy, useful for modals or tooltips that need to escape parent overflow or z-index issues.
ReactDOM.createPortal(<Modal />, document.getElementById('portal-root'));Use proper input validation to prevent XSS, avoid dangerouslySetInnerHTML, use HTTPS, manage environment variables securely, and implement authentication with tokens or cookies properly.
Pass data from parent to child via props. To send data back up, pass a callback function from the parent and invoke it in the child with new data.
// Parent
<Child onSave={setValue} />
// Child
props.onSave('updated');Simply return JSX markup from a function. For static content, you don’t need state or hooks.
function Table(){ return (<table><tr><td>No data</td></tr></table>); }Hooks use functions and closures for state and lifecycle, while classes use `this.state` and methods. Hooks allow logic reuse and simpler composition.
Wrap components in React.memo, memoize functions and values, and avoid passing new objects or inline functions on every render.
React apps can be optimized by using memoization (React.memo, useMemo, useCallback), code-splitting, lazy loading, virtualization for lists, and avoiding unnecessary re-renders by properly managing dependencies and keys.
Main features include the use of Virtual DOM for performance, component-based architecture for reusability, one-way data flow for predictability, and JSX for writing UI with HTML-like syntax inside JavaScript.
useEffect() is used to perform side effects like fetching data, updating the DOM, or setting up subscriptions after render. It replaces lifecycle methods like componentDidMount and componentDidUpdate.
useEffect(() => {
console.log('Effect runs after render');
}, []);Yes, React can be written without JSX by using React.createElement() directly. JSX is just a syntax sugar that makes code easier to read but not mandatory.
const element = React.createElement('h1', null, 'Hello React without JSX');Keys are unique identifiers for elements in a list. They help React know which items have changed, been added, or removed, improving rendering efficiency and preventing re-rendering errors.
const list = items.map(item => <li key={item.id}>{item.name}</li>);Keys should be used when rendering lists of elements. Without them, React cannot track item changes properly, leading to wrong re-renders or performance issues.
You can avoid prop drilling by using React Context API, Redux, Zustand, or custom hooks. These allow you to share data globally without passing props through multiple levels.
Refs let you directly access a DOM element. In uncontrolled components, you use refs to read form values without React managing the input state.
const inputRef = useRef();
const handleSubmit = () => {
alert(inputRef.current.value);
};Functional components are simple JavaScript functions that return JSX. Class components are ES6 classes that extend React.Component and use a render() method. Functional components are now preferred because they are simpler and support Hooks.
// Functional Component
function Welcome() {
return <h1>Hello!</h1>;
}
// Class Component
class Welcome extends React.Component {
render() {
return <h1>Hello!</h1>;
}
}Functional components are lightweight and rely on Hooks for state and lifecycle. Class components use the render() method, have access to lifecycle methods, and use this.state. Hooks made functional components capable of everything classes can do with less code.
In functional components, props are received as function arguments. In class components, they are accessed via this.props. Props are read-only in both cases.
// Functional
function Hello(props) { return <p>{props.name}</p>; }
// Class
class Hello extends React.Component { render() { return <p>{this.props.name}</p>; } }In class components, state is managed with this.state and updated using setState(). In functional components, state is handled with the useState() Hook. Both trigger re-renders when the state changes.
// Functional
const [count, setCount] = useState(0);
// Class
this.state = { count: 0 };
this.setState({ count: this.state.count + 1 });useState() is a Hook that allows you to add state to functional components. It returns an array with the current state and a function to update it. When you call the setter function, React re-renders the component.
const [name, setName] = useState('Guest');
setName('John'); // updates state and re-renders componentIn controlled components, form data is handled by React state. In uncontrolled components, the DOM itself manages the input value using refs. Controlled components provide better validation and consistency.
// Controlled
<input value={text} onChange={(e) => setText(e.target.value)} />
// Uncontrolled
<input ref={inputRef} />Controlled components make React the single source of truth for input values. This gives better control for validation, conditionally disabling inputs, and synchronizing with state.
setState() is used to update a class component’s state. It merges the new values with the existing state and triggers a re-render.
this.setState({ count: this.state.count + 1 });Directly changing state (like this.state.count = 1) won’t trigger a re-render and can cause bugs. Always use setState() or Hooks to update state safely.
Side effects are operations that affect something outside the component, like data fetching, subscriptions, or manually changing the DOM. These are handled using the useEffect Hook.
There are two types: effects without cleanup (like API calls or logging) and effects with cleanup (like removing event listeners or cancelling timers). useEffect can handle both types using return functions.
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer); // cleanup
}, []);React cleans up side effects automatically when a component unmounts or before the effect runs again. Returning a cleanup function inside useEffect prevents memory leaks.
State represents the internal data of a component that can change over time and cause re-renders when updated.
The useEffect hook accepts a function and an optional dependency array. The effect runs when one of the dependencies changes. An empty array runs it only once after mount.
useEffect(() => {
console.log('Runs on count change');
}, [count]);React compares each dependency value on re-render. If any value changes, the effect re-runs. This helps control when side effects occur and avoid unnecessary work.
Hooks must be called at the top level of a component or custom hook, not inside loops, conditions, or nested functions. They must only be called inside React functions.
useRef() creates a mutable reference that persists across renders. It is commonly used to access DOM elements directly or store mutable values without causing re-renders.
const inputRef = useRef(null);
<input ref={inputRef} />;Refs are used to access or modify DOM elements directly, store previous values, and hold data that doesn’t need to trigger re-renders.
Refs let Hooks store values that survive re-renders without updating the UI. This is useful for timers, external libraries, or manual DOM access.
Create a custom hook when you have reusable logic that involves React Hooks, like fetching data, handling input, or subscribing to events. It keeps your code clean and DRY.
Custom hooks make logic reusable, easy to test, and separate UI from logic. They also simplify large components by organizing related logic together.
useEffect handles side effects like API calls or DOM updates after rendering. It is the Hook version of lifecycle methods.
useState provides local state in functional components. It returns a value and a function to update it.
Hooks can only be called from functional components or other custom hooks, not from regular functions or class components.
Context API provides a Provider and Consumer pattern that lets you store and access global data. Components can subscribe to context updates directly, avoiding prop drilling.
A Higher-Order Component is a function that takes a component and returns a new component with extra functionality. It’s often used for cross-cutting concerns like logging or authentication.
function withLogger(Wrapped) {
return function(props) {
console.log('Props:', props);
return <Wrapped {...props} />;
};
}Both reuse logic across components. HOCs wrap components and add behavior, while custom hooks share logic using functions. Hooks are simpler and avoid nesting issues caused by HOCs.
Render props is a technique for sharing logic using a prop whose value is a function. The function returns UI based on data passed to it.
<DataProvider render={(data) => <List items={data} />} />;Error boundaries are React components that catch JavaScript errors in child components during rendering. They prevent entire app crashes by displaying fallback UIs.
Errors can be caught using getDerivedStateFromError and componentDidCatch lifecycle methods. These handle render-time errors gracefully.
Reconciliation is React’s process of comparing Virtual DOM trees to decide which parts of the UI need to update. Only changed elements are re-rendered, improving performance.
React re-renders components when their state or props change. It uses a diffing algorithm to update only the affected parts of the DOM.
Pure Components and memoized functions skip re-renders when inputs don’t change. React.memo prevents re-rendering of functional components, useMemo caches computed values, and useCallback caches functions.
const MemoComp = React.memo(MyComponent); const memoValue = useMemo(() => computeExpensive(value), [value]); const memoFn = useCallback(() => handleClick(id), [id]);
In React Router v6, you can redirect users using the Navigate component after successful login. Once authentication succeeds, set a state like isLoggedIn to true and conditionally render <Navigate to='/dashboard' /> to send the user to the dashboard automatically.
if (isLoggedIn) return <Navigate to='/dashboard' />; else return <LoginForm />;
<Redirect> was used in React Router v5 for navigation. In React Router v6, it was replaced with <Navigate>. <Navigate> is a declarative way to redirect users to another route programmatically and is simpler to use with hooks and state.
<Navigate to='/home' replace />
Dynamic routes let you match variable segments in URLs, such as user IDs or product IDs. They are defined using a colon prefix like ':id', and React Router provides these values via the useParams() hook.
<Route path='/user/:id' element={<UserProfile />} />;
const { id } = useParams();Create a wrapper route that checks if the user is authenticated. If not, redirect them to login. This ensures only logged-in users can access certain pages.
const PrivateRoute = ({ children }) => isAuth ? children : <Navigate to='/login' />;Code splitting divides large bundles into smaller chunks, so only the code needed for a page loads. It reduces initial load time and improves app performance. It’s done using dynamic imports or React.lazy().
const About = React.lazy(() => import('./About'));Use React.lazy() to load components only when needed, wrapped inside a <Suspense> fallback. This helps reduce bundle size and speeds up initial load.
const Contact = React.lazy(() => import('./Contact'));
<Suspense fallback={<p>Loading...</p>}><Contact /></Suspense>Global state can be handled using Redux for predictable centralized state, Context API for lightweight shared state, or Zustand for simpler and faster store-based state management without boilerplate.
Fetch and Axios are used for HTTP requests. React Query helps manage server state with caching, auto refetching, and error handling. Always handle loading and error states during fetch operations.
useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(setData)
.catch(console.error);
}, []);When a component unmounts during an async call, you should cancel ongoing operations. This can be done with AbortController, cleanup functions in useEffect, or checking mounted flags before updating state.
useEffect(() => {
const controller = new AbortController();
fetch('/api', { signal: controller.signal });
return () => controller.abort();
}, []);Use controlled components to manage input values through React state. For validation, libraries like Formik, React Hook Form, or Yup help manage form state, validation, and submission easily.
The command 'npm install -g create-react-app' globally installs the tool for creating new React projects quickly.
Webpack is a module bundler that compiles and optimizes JavaScript, CSS, and assets into one or more bundles for production use.
For small apps, Context and Hooks can replace Redux. For large apps with complex state flows and middleware needs, Redux remains better suited.
You can create a new React project using Create React App or Vite. For CRA, run `npx create-react-app my-app`, then `cd my-app` and `npm start`. For Vite, run `npm create vite@latest my-app -- --template react`, install dependencies, and start with `npm run dev`. Both provide an optimized development setup with hot reload and bundling.
npx create-react-app my-app # or npm create vite@latest my-app -- --template react
A typical React app contains `src` for code, `public` for static assets, `package.json` for dependencies, `node_modules` for installed packages, and configuration files like `.gitignore` and `README.md`. Inside `src`, you’ll find `index.js` and `App.js` as entry points.
package.json lists your app’s metadata, scripts, and dependencies. It tells npm which libraries to install and how to run build or start commands. Dependencies are runtime libraries; devDependencies are for development tools like ESLint or Webpack.
JSX isn’t understood by browsers directly. The build tool (Babel) transpiles JSX into `React.createElement()` calls that produce virtual DOM objects. This keeps code readable while still working with standard JavaScript.
<div>Hello</div> ➜ React.createElement('div', null, 'Hello')Keep the input value in state and filter a list based on it. Controlled inputs keep the displayed value in sync with React state, enabling instant updates and validation.
const [search,setSearch]=useState('');
const filtered=data.filter(i=>i.name.includes(search));A custom hook like `useForm` can manage form state and validation logic. It tracks values, errors, and touched fields. You can combine it with Yup for schema-based validation.
You can build a custom hook that syncs state with localStorage. Whenever state changes, save it to storage and initialize from storage on load.
function useLocal(key,init){
const [val,setVal]=useState(()=>JSON.parse(localStorage.getItem(key))||init);
useEffect(()=>localStorage.setItem(key,JSON.stringify(val)),[val]);
return [val,setVal];
}Call the API inside useEffect after the first render, update state with results, and handle errors gracefully. Axios simplifies HTTP requests and error handling.
useEffect(()=>{axios.get('/api').then(r=>setData(r.data)).catch(e=>setError(e));},[]);Use three pieces of state: data, loading, and error. Set loading true before fetch, update data on success, and show fallback UI on error.
if(loading)return <p>Loading...</p>;
if(error)return <p>Error!</p>;
return <DataList data={data}/>;Map over an array and render a child component for each item. Provide a unique key prop to help React track changes efficiently.
{users.map(u=><UserCard key={u.id} user={u}/>)}It runs the development server (using Vite or webpack-dev-server) and auto-reloads on code changes, serving the app at localhost.
Conditional rendering shows components based on state or props conditions using ternaries or logical AND operators.
{isLoggedIn ? <Dashboard/> : <Login/>}Auth-based apps show different UI for logged-in users. Conditional rendering hides private components until the user is authenticated.
Hooks are lightweight and reduce boilerplate, but improper use of effects can cause extra renders. With memoization, they perform equally or better.
Keys must be unique only among siblings in a list, not globally. They help React track which list items change during rendering.
React Context allows data to be shared globally across components without passing props manually at every level. It is useful for themes, authentication, and global state.
const ThemeContext = React.createContext('light');
<ThemeContext.Provider value='dark'><App/></ThemeContext.Provider>;An error boundary is implemented using class components that define static getDerivedStateFromError() and componentDidCatch(). These catch and handle render errors.
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() { return { hasError: true }; }
componentDidCatch(error, info) { console.log(error, info); }
render() { return this.state.hasError ? <h3>Error!</h3> : this.props.children; }
}Unnecessary re-renders happen when state or props change unnecessarily, or when functions or objects are recreated each render. Prevent them using React.memo, useMemo, useCallback, and by avoiding direct mutations of state.
Keys help React identify which elements changed, added, or removed in a list. This allows React to re-render only the modified items instead of the whole list, improving performance.
{items.map(item => <li key={item.id}>{item.name}</li>)}React is flexible, integrates easily, supports SSR, and offers performance benefits with Virtual DOM.
Use ES module import syntax and include the component in JSX. Ensure it’s exported from its file with `export default SearchItem`.
import SearchItem from './SearchItem';
function App(){ return <SearchItem/>; }Lifecycle methods manage setup and cleanup during a component’s life. Examples include componentDidMount, componentDidUpdate, and componentWillUnmount. Hooks like useEffect replace these.
useParams() retrieves URL parameters like /user/:id, while useSearchParams() or URLSearchParams helps read query strings like ?sort=desc. These hooks simplify dynamic navigation and filtering in apps.
const { id } = useParams();
const [query] = useSearchParams();
const sort = query.get('sort');React is an open-source JavaScript library developed by Facebook (now Meta) for building user interfaces, especially single-page applications. It helps developers create reusable UI components that update efficiently when data changes.
`index.js` is the main entry that renders the root component into the DOM using `ReactDOM.createRoot`. `App.js` is the top-level component where you compose routes and layout.
ReactDOM.createRoot(document.getElementById('root')).render(<App />);useState manages component state; useEffect runs side effects after render. For example, updating the document title when count changes.
function Counter(){
const [count,setCount]=useState(0);
useEffect(()=>{document.title=`Count ${count}`;},[count]);
return <button onClick={()=>setCount(count+1)}>Add</button>;
}Effects without cleanup run once and don’t need cleanup, like fetching data. Effects with cleanup return a function that removes subscriptions or listeners when the component unmounts.
useEffect(() => {
const timer = setInterval(() => console.log('tick'), 1000);
return () => clearInterval(timer);
}, []);Custom hooks are reusable functions that use React’s built-in hooks. They allow you to extract logic from components and reuse it across multiple components.
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}