Skip to content

React JS Interview Questions for 1 Year Experience

40 questions with answers for candidates with 1 year of experience — 17 easy, 22 medium, 1 hard.

What interviewers expect: 1 year experience

With one year of experience, interviewers expect you to have shipped real features. Questions cover hooks in depth, custom hooks, API integration with loading and error states, forms with validation, React Router and a basic state library. You may get a machine coding round building a small feature in 60 to 90 minutes with clean components.

This set is weighted towards React Fundamentals (9), Props and State (8), Testing and Debugging (6), Routing and Forms (4).

Custom hooks and effect cleanup API integration patterns React Hook Form and validation Machine coding practice
Solved at this levelStart practicing
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
3 questions free Unlock the rest in seconds
01

In development your API call inside useEffect fires twice, but only once in production. Why does this happen, and what does StrictMode do?

Save to ▾
Show answer
StrictMode is a development-only wrapper that helps find bugs. It renders components twice to catch impure rendering, and mounts, unmounts and remounts components to check that effects clean up properly. This is why a fetch in useEffect may appear to fire twice locally. It does not happen in production. The fix is to write proper cleanup, not to remove StrictMode.
02

What is the difference between getBy, queryBy and findBy queries?

Save to ▾
Show answer
getBy returns the element or throws immediately if it is missing, so use it when the element should exist. queryBy returns null instead of throwing, which is the right choice to assert something is not present: expect(screen.queryByText('Error')).not.toBeInTheDocument(). findBy returns a promise and retries until the element appears or times out, used for content that appears after async work. Each has an AllBy variant for multiple elements.
03

You import a component and get the error 'Element type is invalid: expected a string or a class/function but got undefined'. How do you debug it?

Save to ▾
Show answer
This almost always means the import does not match the export. If the file uses export default Header, import it as import Header from './Header'. If it uses export function Header, import it as import { Header } from './Header'. Also check the file path, circular imports and that the component name starts with a capital letter. Logging the imported value quickly confirms it is undefined.
04

A developer says the app is too slow, based on testing it with the development server. What do you tell them?

Save to ▾
Show answer
The development build includes extra warnings, StrictMode double rendering, checks and unminified code, so it is much slower and can mislead you. Production builds created with npm run build are minified, tree-shaken and optimised. Test performance on the production build, ideally on a mid-range Android phone with throttled network, because many Indian users browse on such devices and slower connections.
05

What is the Context API and when should you use it?

Save to ▾
Show answer
Context lets a parent provide a value to any component below it without passing props through every level. You create it with createContext, provide a value high in the tree and read it with useContext. It is ideal for values that many components need and that change rarely, such as theme, language, logged-in user or feature flags. It is not a full replacement for a state management library.
06

How do you type props for a component in TypeScript?

Save to ▾
Show answer
Define a type or interface and annotate the destructured props. type ProductCardProps = { title: string; price: number; tags?: string[]; onAdd: (id: string) => void; children?: React.ReactNode; }; function ProductCard({ title, price, tags = [], onAdd, children }: ProductCardProps) { return <div onClick={() => onAdd(title)}>{title} - Rs {price}{children}</div>; }
07

How do you handle a form with multiple controlled inputs using one change handler?

Save to ▾
Show answer
Use the input's name attribute to update the right field. function SignupForm() { const [form, setForm] = useState({ name: '', email: '', city: '' }); const handleChange = e => { const { name, value } = e.target; setForm(f => ({ ...f, [name]: value })); }; const handleSubmit = e => { e.preventDefault(); console.log(form); }; return ( <form onSubmit={handleSubmit}> <input name="name" value={form.name} onChange={handleChange} /> <input name="email" value={form.email} onChange={handleChange} /> <button>Submit</button> </form> ); }
08

Should you keep related values in one state object or several useState calls?

Save to ▾
Show answer
Group values that always change together, like x and y coordinates, into one object. Keep unrelated values in separate useState calls, which makes updates simpler and avoids accidentally overwriting fields. Avoid contradictory or duplicated state, such as isLoading and isError both being true. When many values change together through clear events, useReducer is often a cleaner choice than a big object.
09

What kinds of tests are written for a React application?

Save to ▾
Show answer
Unit tests check small pieces like utility functions, reducers and custom hooks. Component or integration tests render components with their children and check behaviour the user sees, usually with React Testing Library and Vitest or Jest. End-to-end tests run the full app in a real browser with Playwright or Cypress, covering flows like login and checkout. Static checks with TypeScript and ESLint catch many bugs before tests run.
10

How do you update objects and arrays in state without mutating them?

Save to ▾
Show answer
Always create new copies so React detects the change by reference. // object setUser(u => ({ ...u, city: 'Pune' })); // add to array setItems(list => [...list, newItem]); // remove setItems(list => list.filter(i => i.id !== id)); // update one item setItems(list => list.map(i => i.id === id ? { ...i, done: true } : i));
11

Which queries should you prefer in React Testing Library and why?

Save to ▾
Show answer
Prefer queries accessible to everyone: getByRole (with the name option) first, then getByLabelText for form fields, getByPlaceholderText, getByText and getByDisplayValue. Use getByAltText and getByTitle for images and titles. getByTestId is a last resort when nothing else works. Role-based queries also check accessibility, because if a button cannot be found by role and name, screen reader users will struggle too.
12

What is a Higher-Order Component and is it still used?

Save to ▾
Show answer
A Higher-Order Component is a function that takes a component and returns a new component with extra behaviour, for example withAuth(Profile) that redirects unauthenticated users. HOCs were common for sharing logic like routing or Redux connect. Today custom hooks are preferred because they avoid wrapper nesting, prop name collisions and confusing component trees. You will still see HOCs in older codebases.
13

What is RTK Query?

Save to ▾
Show answer
RTK Query is the data fetching and caching tool included in Redux Toolkit. You define an API with createApi and endpoints, and it auto-generates hooks like useGetProductsQuery and useAddProductMutation. It handles loading states, caching, deduplicating requests, refetching and cache invalidation through tags. It removes most hand-written thunks and reducers for server data in Redux-based apps.
14

Describe a time you disagreed with a teammate about how a component should be designed.

Save to ▾
Show answer
Situation: a teammate wanted one large Table component with over twenty boolean props. Task: we needed a design that both of us and future developers could maintain. Action: I built a quick prototype using composition with Table.Header and Table.Row, and we compared both on two real screens. Result: the team chose composition, prop count dropped sharply, and we agreed to prototype before arguing in future.
15

Write a simple counter component with increment, decrement and reset buttons.

Save to ▾
Show answer
A counter is the classic useState example. Use the functional updater so each click works on the latest value. import { useState } from 'react'; export default function Counter() { const [count, setCount] = useState(0); return ( <div> <h2>{count}</h2> <button onClick={() => setCount(c => c + 1)}>+</button> <button onClick={() => setCount(c => c - 1)}>-</button> <button onClick={() => setCount(0)}>Reset</button> </div> ); }
16

Five components on one page each fetch the same user profile, causing duplicate API calls. How would you fix this?

Save to ▾
Show answer
Lift the data fetching into a shared cache instead of each component fetching on its own. With TanStack Query or RTK Query, all components using the same query key share one request and one cached result, and get updates together. Alternatively, fetch once in a parent or route loader and pass data down. This also removes inconsistent loading spinners across the page.
17

What is the difference between props and state?

Save to ▾
Show answer
Props are inputs passed from a parent component and are read-only inside the child. State is data owned and managed by the component itself with useState or useReducer, and changing it triggers a re-render. A simple rule: if a value comes from outside and the component does not change it, it is a prop; if it changes over time due to user action or data loading, it is state.
18

Why do you want to work as a React developer?

Save to ▾
Show answer
I enjoy building things people use directly, and React lets me turn designs into fast, interactive screens. During my training I built three projects with React, TypeScript and APIs, and I liked how components make code reusable. React also has strong demand across startups and service companies in India, a large community and paths into Next.js and React Native, so I see long-term growth in this role.
19

What is the difference between functional components and class components?

Save to ▾
Show answer
Class components extend React.Component, use this.state and lifecycle methods like componentDidMount. Functional components are plain functions that return JSX and use hooks such as useState and useEffect for state and side effects. Modern React code is written almost entirely with functional components because they are shorter, easier to test and reuse logic through custom hooks. Class components are still needed only for error boundaries.
20

Why is React Hook Form popular?

Save to ▾
Show answer
React Hook Form registers inputs as uncontrolled by default and reads values through refs, so typing does not re-render the whole form. This makes large forms fast. It provides validation, error messages, field arrays for dynamic rows, and integrates with Zod or Yup through resolvers. It has a small bundle and works with UI libraries through a Controller component for custom controlled inputs.
21

What is the difference between the App Router and the Pages Router in Next.js?

Save to ▾
Show answer
The Pages Router uses the pages directory with getServerSideProps and getStaticProps for data. The App Router, the recommended default, uses the app directory with nested layouts, React Server Components by default, streaming with loading.js, error.js boundaries and Server Functions. Data is fetched directly in async server components. Many older projects still use Pages Router, and both can coexist during migration.
22

What are portals and when would you use them?

Save to ▾
Show answer
A portal renders children into a DOM node outside the parent component's DOM hierarchy while keeping them in the same React tree, so context and event bubbling still work. import { createPortal } from 'react-dom'; function Modal({ children }) { return createPortal( <div className="modal">{children}</div>, document.getElementById('modal-root') ); } They are used for modals, tooltips and dropdowns that must escape overflow hidden or z-index issues.
23

How do you navigate programmatically after a form submits?

Save to ▾
Show answer
Use the useNavigate hook. import { useNavigate } from 'react-router'; function CheckoutForm() { const navigate = useNavigate(); async function handleSubmit(e) { e.preventDefault(); const order = await placeOrder(); navigate(`/orders/${order.id}`, { replace: true }); } return <form onSubmit={handleSubmit}>...</form>; } replace: true stops the user from going back to the submitted form; navigate(-1) goes back.
24

Your component fetches data in useEffect and the network tab shows thousands of requests in a loop. What could cause it?

Save to ▾
Show answer
Common causes are a missing dependency array, so the effect runs after every render and its setState triggers another render, or a dependency that is a new object or array each render, like options={{ page: 1 }}. Since Object.is compares by reference, the effect always sees a change. Fix by adding correct dependencies, depending on primitive values, or memoising the object with useMemo.
25

A developer stores fullName in state and updates it in a useEffect whenever firstName or lastName changes. What would you suggest?

Save to ▾
Show answer
This is redundant derived state. It causes an extra render and risks the values going out of sync. Compute it during render instead: const fullName = firstName + ' ' + lastName. If the calculation is expensive, wrap it in useMemo. As a rule, if a value can be calculated from existing props or state, do not store it in state and do not sync it with an effect.
26

Explain the Virtual DOM and reconciliation in React.

Save to ▾
Show answer
The Virtual DOM is a lightweight JavaScript tree describing the UI. When state changes, React renders a new tree, compares it with the previous one (reconciliation, or diffing) and applies only the minimal real DOM changes. It assumes elements of different types produce different trees and uses keys to match list items, which makes the diff roughly linear instead of very expensive full tree comparison.
27

What is the difference between useMemo and useCallback?

Save to ▾
Show answer
useMemo caches the result of a calculation between renders, like a filtered list: useMemo(() => filter(items, q), [items, q]). useCallback caches a function definition itself: useCallback(fn, deps), which equals useMemo(() => fn, deps). Both are performance tools, useful when passing values to React.memo children or effect dependencies. With the React Compiler enabled, much of this manual memoisation becomes unnecessary.
28

How do you add multiple languages to a React app?

Save to ▾
Show answer
Use an i18n library such as react-i18next or, in Next.js, next-intl. Store translations in JSON files per locale, reference keys like t('cart.title') instead of hard-coded text, and handle plurals, dates, numbers and currency with Intl APIs. Put the locale in the URL, like /hi/products, for SEO and shareable links. For Indian audiences, check fonts for Devanagari and other scripts and test longer translated text.
29

How do you create a protected route that redirects users who are not logged in?

Save to ▾
Show answer
Create a wrapper that checks auth and either renders the child routes or redirects. import { Navigate, Outlet, useLocation } from 'react-router'; function RequireAuth() { const { user } = useAuth(); const location = useLocation(); if (!user) return <Navigate to="/login" replace state={{ from: location }} />; return <Outlet />; } <Route element={<RequireAuth />}> <Route path="/account" element={<Account />} /> </Route> The server must still enforce authorisation.
30

Your team has hundreds of snapshot tests that developers update blindly whenever they fail. What are the drawbacks of snapshot tests and what would you suggest?

Save to ▾
Show answer
A snapshot test saves the rendered output to a file and fails when future output differs. It is quick to write and catches unexpected changes. Drawbacks: large snapshots are hard to review, developers often blindly update them, and they fail on harmless markup changes while saying nothing about behaviour. Use small, focused inline snapshots for stable output, and prefer behaviour assertions for most component tests.
31

How do you find what is making a React page slow?

Save to ▾
Show answer
Use the React DevTools Profiler: record an interaction, then check the flame chart for components with long render times and the reason each one re-rendered (enable 'record why each component rendered'). Pair it with the Chrome Performance panel for long tasks, layout and network. Enable highlight updates to spot unnecessary renders. Measure first, fix the biggest cost, then measure again in a production build.
32

How would you update deeply nested state cleanly? Show with Immer.

Save to ▾
Show answer
Manual spreading of nested objects is error prone. Immer lets you write mutating code on a draft and produces an immutable copy. Redux Toolkit uses it internally. import { useImmer } from 'use-immer'; const [form, updateForm] = useImmer({ address: { city: '', pin: '' } }); updateForm(draft => { draft.address.city = 'Noida'; }); Also consider flattening state to avoid deep nesting.
33

What are synthetic events in React?

Save to ▾
Show answer
React wraps native browser events in a SyntheticEvent object that has the same interface (preventDefault, stopPropagation, target) across browsers. Since React 17, listeners are attached to the root container instead of document, which makes it safer to mix multiple React versions. Event pooling was removed, so you can read event properties asynchronously. Handlers are passed as functions, like onClick={handleClick}.
34

Write a custom hook to fetch data with loading and error states.

Save to ▾
Show answer
A custom hook is a function starting with use that combines other hooks. function useFetch(url) { const [state, setState] = useState({ data: null, loading: true, error: null }); useEffect(() => { const ctrl = new AbortController(); setState(s => ({ ...s, loading: true })); fetch(url, { signal: ctrl.signal }) .then(r => { if (!r.ok) throw new Error(r.status); return r.json(); }) .then(data => setState({ data, loading: false, error: null })) .catch(err => { if (err.name !== 'AbortError') setState({ data: null, loading: false, error: err }); }); return () => ctrl.abort(); }, [url]); return state; }
35

How do you test a component that fetches data from an API?

Save to ▾
Show answer
Mock the network, not fetch itself, using Mock Service Worker (MSW), then wait for the UI. const server = setupServer( http.get('/api/users', () => HttpResponse.json([{ id: 1, name: 'Asha' }])) ); beforeAll(() => server.listen()); afterEach(() => server.resetHandlers()); afterAll(() => server.close()); test('shows users', async () => { render(<Users />); expect(await screen.findByText('Asha')).toBeInTheDocument(); });
36

How do you fetch data in a Next.js App Router page?

Save to ▾
Show answer
Make the page an async Server Component and await data directly. // app/products/[id]/page.tsx export default async function ProductPage({ params }) { const { id } = await params; const product = await getProduct(id); if (!product) notFound(); return ( <main> <h1>{product.name}</h1> <AddToCartButton id={id} /> </main> ); } AddToCartButton is a Client Component. In recent Next.js versions params is a promise.
37

What are keys in React lists and why are they required?

Save to ▾
Show answer
A key is a stable, unique identifier given to each element in a list so React can tell which items were added, removed or moved between renders. Without good keys React may reuse the wrong DOM nodes or component state. Use an id from your data, for example key={user.id}. Keys only need to be unique among siblings, not across the whole app.
38

What does lifting state up mean?

Save to ▾
Show answer
Lifting state up means moving shared state to the closest common parent of the components that need it. The parent holds the state and passes the value and a setter callback down as props. For example, a temperature input and a converter display both read from state kept in their parent. This keeps a single source of truth instead of two components trying to stay in sync.
39

You see the error 'Rendered more hooks than during the previous render'. What is wrong?

Save to ▾
Show answer
A hook is being called conditionally or after an early return, so the number of hooks changes between renders. For example, if (!user) return null; placed before a useState call. React matches hooks by call order, so this breaks. Move all hook calls to the top of the component before any condition or early return, and put the condition inside the hook logic instead.
40

What is the guiding philosophy of React Testing Library?

Save to ▾
Show answer
React Testing Library encourages testing components the way users use them, not their internal implementation. You find elements by role, label or text, interact with them through user events and assert what appears on screen. You avoid checking state variables or component instances. Its motto is that the more your tests resemble the way your software is used, the more confidence they give you, and refactors do not break them.

Frequently asked questions

What is asked in React JS interviews for 1 year of experience?

With one year of experience, interviewers expect you to have shipped real features. Questions cover hooks in depth, custom hooks, API integration with loading and error states, forms with validation, React Router and a basic state library. You may get a machine coding round building a small feature in 60 to 90 minutes with clean components.

How many questions should I practise before a React JS interview?

Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.

Which topics matter most for 1 year of experience?

Focus first on Custom hooks and effect cleanup, API integration patterns, React Hook Form and validation, Machine coding practice.