rjcoder.
React.js
1. What is React?
Answer: React is a JavaScript library for building user interfaces,
particularly single-page applications. It’s used for handling the view layer in
web and mobile apps.
2. What is JSX?
Answer: JSX is a syntax extension for JavaScript, recommended for use
with React. It allows you to write HTML-like code in your JavaScript files,
making it easier to describe what the UI should look like.
3. What is the virtual DOM?
Answer: The virtual DOM is a lightweight copy of the actual DOM in
memory. React uses it to improve performance by minimizing direct
manipulation of the DOM, instead making changes to the virtual DOM and
then efficiently updating the real DOM.
4. What is the difference between state and props?
Answer: Props (short for properties) are read-only and are passed from
parent to child components. State is managed within the component and
can be changed using setState().
5. What is the difference between a functional component and a
class component?
Answer: Functional components are simpler, just JavaScript functions that
return JSX. Class components are more feature-rich, allowing use of
lifecycle methods and local state (prior to the introduction of Hooks).
6. How do you pass data from parent to child components?
Answer: Data is passed from parent to child components via props. The
parent component sets properties on the child component when rendering
it.
Q*: What is the difference between == and ===?
7. What is the purpose of `render()` in React?
Answer: The render() method is required in class components. It returns
the JSX that describes what should be rendered on the screen.
8. What are React Hooks?
Answer: Hooks are functions that let you use state and other React features
in functional components, without writing a class. They were introduced in
React 16.8.
9. Explain the `useState` Hook.
Answer: useState is a Hook that lets you add state to functional
components. It returns an array with the current state value and a function
to update it.
10. What is the `useEffect` Hook used for?
Answer: useEffect is used for side effects in functional components. It
serves a similar purpose to componentDidMount, componentDidUpdate,
and componentWillUnmount in class components.
11. What is conditional rendering in React?
Answer: Conditional rendering in React allows you to render different UI
elements based on certain conditions. This can be done using if statements,
ternary operators, or logical && operator.
12. What is prop drilling and how can it be avoided?
Answer: Prop drilling occurs when props need to be passed through
multiple levels of components. It can be avoided using Context API, Redux,
or composition.
13. How do you create a controlled component?
Answer: A controlled component is one where form data is handled by the
React component’s state. You create it by setting the value of the form
element to a state variable and updating that state in an onChange handler.
14. What is the difference between controlled and uncontrolled
components?
Answer: In controlled components, form data is handled by React state. In
uncontrolled components, form data is handled by the DOM itself.
15. How do you handle forms in React?
Answer: Forms in React are typically handled using controlled components,
where form inputs are controlled by React state. You use onChange
handlers to update the state as the user types.
## Intermediate Level
16. What is the Context API?
Answer: The Context API provides a way to pass data through the
component tree without having to pass props down manually at every level.
It’s designed to share data that can be considered “global” for a tree of
React components.
17. Explain the concept of lifting state up.
Answer: Lifting state up is a pattern used when several components need to
share the same changing data. Instead of keeping the state in child
components, you move it up to their closest common ancestor.
18. What are Higher-Order Components (HOCs)?
Answer: A Higher-Order Component is a function that takes a component
and returns a new component with some additional functionality. It’s a way
to reuse component logic across multiple components.
19. What is the purpose of `React.memo()`?
Answer: React.memo() is a higher-order component that can be used to
optimize functional components by memoizing the result. It prevents
unnecessary re-renders if the props haven’t changed.
20. How does React handle routing?
Answer: React doesn’t have built-in routing. Routing in React applications
is typically handled by libraries like React Router, which allows you to
define routes and map them to components.
21. Explain the `useCallback` Hook.
Answer: useCallback is a hook that returns a memoized version of the
callback function that only changes if one of the dependencies has changed.
It’s useful for optimizing performance in child components.
22. How do you handle error boundaries in React?
Answer: Error boundaries are React components that catch JavaScript
errors anywhere in their child component tree, log those errors, and display
a fallback UI instead of the component tree that crashed.
23. How do you implement server-side rendering with React?
Answer: Server-side rendering can be implemented using frameworks like
Next.js, or manually by using ReactDOMServer’s renderToString method
on the server and hydrating the app on the client.
24. What is the purpose of the `useRef` Hook?
Answer: useRef returns a mutable ref object whose .current property is
initialized to the passed argument. It’s commonly used to access DOM
elements directly or to keep mutable values across renders without causing
re-renders.
25. How do you implement form validation in React?
Answer: Form validation in React can be implemented using controlled
components, where you validate the input in the onChange handler and
store the validation state. Libraries like Formik can also be used for more
complex forms.
26. How do you handle asynchronous operations in React?
Answer: Asynchronous operations in React can be handled using useEffect
for side effects, async/await syntax, or libraries like Redux-Thunk or
Redux-Saga for more complex state management.
## Advanced Level
27. How do you create a custom Hook?
Answer: Custom Hooks are created by extracting component logic into
reusable functions. They can call other Hooks and should start with the
word “use” to follow the Hook naming convention.
28. How do you implement a debounce function in React?
Answer: A debounce function can be implemented using useCallback and
useEffect Hooks, along with setTimeout to delay the execution of a
function.
29. What are the differences between React’s `useState` and
`useReducer` Hooks?
Answer: useState is simpler and good for managing independent pieces of
state, while useReducer is preferable for complex state logic, especially
when the next state depends on the previous one.
Coding Examples
30. Write a simple counter component using the `useState`
Hook.
import React, { useState } from ‘react’;
function Counter(){
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
**31. Implement a basic form with React.*
import React, { useState } from ‘react’;
function SimpleForm(){
const [formData, setFormData] = useState({ name: ‘’, email: ‘’ });
const handleChange = (e) =>{
setFormData({ …formData, [e.target.name]: e.target.value });
};
const handleSubmit = (e) =>{
e.preventDefault();
console.log(‘Form submitted:’, formData);
};
return (
<form onSubmit={handleSubmit}>
<input type=”text” name=”name” value={formData.name}
onChange={handleChange} placeholder=”Name” />
<input type=”email” name=”email” value={formData.email}
onChange={handleChange} placeholder=”Email” />
<button type=”submit”>Submit</button>
</form>
);
}
**32. Create a custom Hook for fetching data.**
import { useState, useEffect } from ‘react’;
function useFetch(url){
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() =>{
fetch(url)
.then((response) => response.json())
.then((data) =>{
setData(data);
setLoading(false);
})
.catch((error) =>{
setError(error);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
**33. Implement a basic routing setup using React Router.**
import React from ‘react’;
import { BrowserRouter as Router, Route, Link, Switch } from
‘react-router-dom’;
function App(){
return (
<Router>
<nav>
<ul>
<li><Link to=”/”>Home</Link></li>
<li><Link to=”/about”>About</Link></li>
<li><Link to=”/contact”>Contact</Link></li>
</ul>
</nav>
<Switch>
<Route exact path=”/” component={Home} />
<Route path=”/about” component={About} />
<Route path=”/contact” component={Contact} />
</Switch>
</Router>
);
}
**34. Create a simple animation using React Spring.**
import React from ‘react’;
import { useSpring, animated } from ‘react-spring’;
function AnimatedComponent(){
const props = useSpring({ opacity: 1, from: { opacity: 0 } });
return <animated.div style={props}>I will fade in</animated.div>;
**35. Implement a basic Redux setup with React.**
// actions.js
export const increment = () => ({ type: ‘INCREMENT’ });
export const decrement = () => ({ type: ‘DECREMENT’ });
// reducer.js
const initialState = { count: 0 };
function counterReducer(state = initialState, action){
switch (action.type){
case ‘INCREMENT’:
return { …state, count: state.count + 1 };
case ‘DECREMENT’:
return { …state, count: state.count — 1 };
default:
return state;
// Component
import React from ‘react’;
import { useSelector, useDispatch } from ‘react-redux’;
import { increment, decrement } from ‘./actions’;
function Counter(){
const count = useSelector((state) => state.count);
const dispatch = useDispatch();
return (
<div>
<p>Count: {count}</p>
<button onClick={() => dispatch(increment())}>Increment</button>
<button onClick={() => dispatch(decrement())}>Decrement</button>
</div>
);
**36. Use the `useReducer` Hook for complex state
management.**
import React, { useReducer } from ‘react’;
const initialState = { count: 0 };
function reducer(state, action){
switch (action.type){
case ‘increment’:
return { count: state.count + 1 };
case ‘decrement’:
return { count: state.count — 1 };
default:
throw new Error();
}
function Counter(){
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
Count: {state.count}
<button onClick={() => dispatch({ type: ‘increment’ })}>+</button>
<button onClick={() => dispatch({ type: ‘decrement’ })}>-</button>
</>
);