Top React Interview Questions And Answers 2023
1. What is ReactJS?
2. What is JSX?
const element = <h1>Hello, JSX!</h1>;
const element = React.createElement('h1', null, 'Hello, JSX!');
3. Explain the Virtual DOM and its advantages.
4. What are props in React?
5. What is state in React?
6. What is the difference between state and props?
7. What are React hooks?
- useState: useState hook allows functional components to manage state. It takes an initial value and returns the current state value and a function to update it.
const [count, setCount] = useState(0);
- useEffect: useEffect hook is used to manage side effects in functional components, such as data fetching, DOM manipulation, and more. It's called after rendering and can be used to perform cleanup as well.
useEffect(() => {
// Side effect code here
return () => {
// Cleanup code here
};
}, [dependency]);
- useContext: useContext hook allows you to access context values provided by an ancestor Context.Provider component. It avoids the need for prop drilling by allowing components to directly consume context values.
const socket = useContext(SocketContext);
- useCallback: useCallback hook used to memoize a callback function, preventing unnecessary re-creation of the function during re-renders. It's useful for optimizing performance in components that depend on callbacks.
const memoizedCallback = useCallback(() => {...}, [dependency]);
- useMemo: useMemo hook used to memoize a value, preventing re-computation during re-renders. It's useful for optimizing performance in components that compute expensive values.
const memoizedValue = useMemo(() => computeValue(dependency), [dependency]);
-
useRef: useRef is used to create a mutable reference that persists across renders. It's often used to access DOM elements.
const inputRef = useRef();
8. What is a higher-order component (HOC)?
import React from 'react';
// A functional higher-order component that adds a background color to a component
const withBackgroundColor = (WrappedComponent, color) => {
return (props) => (
<div style={{ backgroundColor: color }}>
<WrappedComponent {...props} />
</div>
);
};
// Component that will receive the background color enhancement from the HOC
const Content = ({ text }) => {
return <div>{text}</div>;
};
// Wrap the Content component with the withBackgroundColor HOC
const ContentWithBackground = withBackgroundColor(Content, 'lightblue');
// Usage of the enhanced component
const App = () => {
return (
<div>
<h1>Functional Higher-Order Component Example</h1>
<ContentWithBackground text="Hello, HOC!" />
</div>
);
};
export default App;
9. Explain the concept of Context in React.
import React, { createContext, useContext } from 'react';
// Create a context
const ThemeContext = createContext();
// Provide the context value at the top of the component tree
function App() {
const theme = 'dark';
return (
<ThemeContext.Provider value={theme}>
<Navbar />
<Sidebar />
</ThemeContext.Provider>
);
}
// Consume the context value using a functional component and useContext
function Navbar() {
const theme = useContext(ThemeContext);
return <div>Current theme: {theme}</div>;
}
// Consume the context value using a functional component and useContext
function Sidebar() {
const theme = useContext(ThemeContext);
return <div>Current theme: {theme}</div>;
}
export default App;
10. What is Redux?
11. What are controlled components?
import React, { useState } from 'react';
function ControlledComponent() {
const [inputValue, setInputValue] = useState('');
const handleInputChange = (event) => {
setInputValue(event.target.value);
};
return (
<input
type="text"
value={inputValue}
onChange={handleInputChange}
/>
);
}
12. What are uncontrolled components in React?
import React, { useRef } from 'react';
function UncontrolledComponent() {
const inputRef = useRef();
const handleButtonClick = () => {
// Access input value using the ref
console.log(inputRef.current.value);
};
return (
<div>
<input type="text" ref={inputRef} />
<button onClick={handleButtonClick}>Log Input Value</button>
</div>
);
}
13. What is key prop?
import React from 'react';
const ItemList = ({ items }) => {
return (
<ul>
{items.map(item => (
<li key={item.id}>{item.name}</li>
))}
</ul>
);
};
const App = () => {
const items = [
{ id: 1, name: 'Item 1' },
{ id: 2, name: 'Item 2' },
{ id: 3, name: 'Item 3' }
];
return <ItemList items={items} />;
};
export default App;
14. Explain the concept of "lifting state up."
import React, { useState } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const onIncrement = () => {
setCount(count + 1);
};
return (
<div>
<ChildComponent count={count} onIncrement={onIncrement} />
</div>
);
}
function ChildComponent({ count, onIncrement }) {
return (
<div>
<p>Count: {count}</p>
<button onClick={onIncrement}>Increment</button>
</div>
);
}
export default ParentComponent;
15. What are React fragments?
import React from 'react';
const FragmentExample = () => {
return (
<>
<h1>React Fragments</h1>
<p>This is a paragraph.</p>
</>
);
};
export default FragmentExample;
import React from 'react';
const FragmentExample = () => {
const items = [
{ id: 1, name: 'Alice', age: 25 },
{ id: 2, name: 'Bob', age: 30 },
{ id: 3, name: 'Carol', age: 28 },
];
return (
<div>
{
items.map((item) => (
<React.Fragment key={item.id}>
<h1>React Fragments</h1>
<p>This is a paragraph.</p>
</React.Fragment>
))
}
</div>
);
};
export default FragmentExample;
16. What is PureComponent?
import React, { PureComponent } from 'react';
class MyPureComponent extends PureComponent {
render() {
return <div>{this.props.data}</div>;
}
}
export default MyPureComponent;
Here's an example of PureComponent with a functional component:
import React from 'react';
const MyPureComponent = React.memo(({ data }) => {
return <div>{data}</div>;
});
export default MyPureComponent;
17. Explain the concept of reconciliation in React.
18. What is the purpose of the forwardRef function?
import React, { forwardRef } from 'react';
// Child component using forwardRef
const ChildComponent = forwardRef((props, ref) => {
return <input ref={ref} />;
});
// Parent component using the ChildComponent with a forwarded ref
const ParentComponent = () => {
const inputRef = React.createRef();
const focusInput = () => {
if (inputRef.current) {
inputRef.current.focus();
}
};
return (
<div>
<ChildComponent ref={inputRef} />
<button onClick={focusInput}>Focus Input</button>
</div>
);
};
export default ParentComponent;
19. What is the purpose of the React.memo function?
import React from 'react';
const ExpensiveComponent = ({ data }) => {
// Imagine some complex and time-consuming rendering logic here
console.log('ExpensiveComponent is re-rendered');
return <div>{data}</div>;
};
// Wrap the ExpensiveComponent with React.memo
const MemoizedExpensiveComponent = React.memo(ExpensiveComponent);
const App = () => {
const [count, setCount] = React.useState(0);
const incrementCount = () => {
setCount(count + 1);
};
return (
<div>
<h1>React.memo Example</h1>
<button onClick={incrementCount}>Increment Count</button>
<p>Count: {count}</p>
<MemoizedExpensiveComponent data={count} />
</div>
);
};
export default App;
20. What is the difference between a functional component and a class component?
21. What is server-side rendering (SSR) in React?
22. What is the purpose of the createRef method?
23. What is the differences between useRef and createRef?
24. What is children prop?
In short. children prop allow you to pass components as data to other components.
import React from 'react';
const Card = ({ children }) => {
return (
<div className="card">
{children}
</div>
);
};
const App = () => {
return (
<div>
<Card>
<p>This is the content of the card.</p>
<button>Click Me</button>
</Card>
</div>
);
};
export default App;
25. How can you optimize the performance of a React application?
26. What is lazy loading?
import React, { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => {
return (
<div>
<h1>Lazy Loading Example</h1>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
};
export default App;
27. What is prop drilling in React?
import React from 'react';
const Grandchild = ({ value }) => {
return <p>Value from Prop: {value}</p>;
};
const Child = ({ value }) => {
return <Grandchild value={value} />;
};
const Parent = ({ value }) => {
return <Child value={value} />;
};
const App = () => {
const data = 'Hello, Prop Drilling!';
return <Parent value={data} />;
};
export default App;
28. What is Next.js?
One of the primary benefits of Next.js is its support for server-side rendering (SSR). This means that pages can be rendered on the server and sent as fully-rendered HTML to the client, improving initial page load performance and SEO.
Next.js also supports static site generation(SSG). You can pre-render pages at build time, which can be incredibly fast and is suitable for content that doesn't change frequently.
29. What is Tree-Shaking?
Answer: Tree-shaking refers to the process of eliminating unused code or "dead code" from your JavaScript bundles to reduce their size and improve application performance. It relies on the import and export statements to detect if code modules are exported and imported for use between JavaScript files.
React applications are often built using the Webpack build tool, which has built-in support for tree shaking. Webpack analyzes the import statements in your code and figures out which parts of your codebase are actually used. Any code that is not imported or used in your application is considered dead code.
30. Explain the difference between Shallow Copy vs Deep Copy?
Answer: A shallow copy(Copy by Reference) is an exact copy of the source object whose properties share the same references(memory address). while In deep copy(Copy by Value) an object is copied along with its values. There is no sharing of references between the source and deep-copied objects.
Leave Your Comment