Note
To add new question check CONTRIBUTING.md
Important
Use proper formatting.
Hide/Show table of contents
-
React (aka React.js or ReactJS) is an open-source front-end JavaScript library that is used for building composable user interfaces, especially for single-page applications. It is used for handling view layer for web and mobile apps based on components in a declarative approach.
React was created by Jordan Walke, a software engineer working for Facebook. React was first deployed on Facebook's News Feed in 2011 and on Instagram in 2012.
-
Redux is a state management library for JavaScript applications, often used with libraries like React or Angular. It helps manage the state of an application in a predictable way, making it easier to debug and test. Redux follows a unidirectional data flow, where the state is stored in a single immutable store, and changes are made through dispatched actions.
-
No, you cannot dispatch actions inside a reducer. Reducers are pure functions that take the previous state and an action as arguments and return a new state. They should not have side effects or change the state directly; instead, actions should be dispatched outside of reducers.
-
No, reducers should remain pure and synchronous. They should not perform side effects like making API calls. To handle asynchronous logic, middleware like Redux Thunk or Redux Saga is typically used.
-
Flux is an architectural pattern for building client-side web applications, while Redux is a specific implementation of that pattern. Redux simplifies the Flux architecture by using a single store and a more straightforward API for state management.
-
Thunk and Saga are both middleware for handling asynchronous actions in Redux. Thunk allows you to write action creators that return a function instead of an action, enabling you to dispatch actions conditionally. Redux Saga, on the other hand, uses generator functions to handle complex side effects and is more powerful for managing complex async flows.
-
Reselect is a library used to create memoized selectors in Redux. It helps optimize performance by preventing unnecessary re-renders by only recalculating derived data when the input state changes.
-
Props are used to pass data from parent to child components, while state is used to manage data within a component. Props are immutable and controlled by the parent component, whereas state is mutable and managed within the component itself.
-
Controlled components are form elements whose value is controlled by React state, while uncontrolled components maintain their own internal state. Controlled components are often preferred for better state management and validation.
-
Prop drilling refers to the process of passing data from a parent component to a deeply nested child component through multiple layers of intermediate components. This can lead to code that is hard to maintain and understand. Context API or state management libraries like Redux can help mitigate prop drilling.
-
Next.js is a React framework that enables server-side rendering, static site generation, and API routes. It simplifies the development of React applications by providing routing and performance optimizations out of the box. Current stable version is Next15.
-
A stateful component manages its own state and lifecycle methods, while a stateless component (also known as a functional component) does not manage its own state and simply receives data through props. Stateful components are typically class components, though functional components can also use hooks to manage state.
-
Higher-Order Components (HOCs) are functions that take a component and return a new component. They are used for reusing component logic, such as enhancing components with additional props or behavior.
-
The Virtual DOM is a lightweight representation of the actual DOM, used by React to optimize rendering performance. Shadow DOM is a web standard that allows for encapsulating styles and markup in a component, preventing conflicts. Real DOM is the actual representation of the UI in the browser.
-
React Hooks are functions that allow you to use state and lifecycle features in functional components. Some commonly used hooks include:
-
useState: Manages local component state.Code
import React, { useState } from 'react'; const Counter = () => { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); };
-
useRef: useRef is used to create a mutable reference that persists for the full lifetime of the component. It's often used to access a DOM element directly.Code
import React, { useRef } from 'react'; const InputFocus = () => { const inputRef = useRef(null); const focusInput = () => { if (inputRef.current) { inputRef.current.focus(); } }; return ( <div> <input ref={inputRef} type="text" placeholder="Click the button to focus" /> <button onClick={focusInput}>Focus Input</button> </div> ); };
-
useEffect: Handles side effects like data fetching and subscriptions.Code
import React, { useState, useEffect } from 'react'; const DataFetcher = () => { const [data, setData] = useState(null); useEffect(() => { fetch('https://api.example.com/data') .then(response => response.json()) .then(data => setData(data)); }, []); // Empty dependency array means it runs once on mount return ( <div> {data ? <p>Data: {data}</p> : <p>Loading...</p>} </div> ); };
-
useMemo: Memoizes expensive calculations.Code
import React, { useState, useMemo } from 'react'; const ExpensiveCalculation = ({ number }) => { const calculateFactorial = (num) => { return num <= 0 ? 1 : num * calculateFactorial(num - 1); }; const factorial = useMemo(() => calculateFactorial(number), [number]); return <p>Factorial of {number} is {factorial}</p>; };
-
useContext: Consumes context values.Code
import React, { useContext, createContext } from 'react'; const ThemeContext = createContext('light'); const ThemedComponent = () => { const theme = useContext(ThemeContext); return <div className={theme}>Current theme: {theme}</div>; }; // Usage in App component const App = () => ( <ThemeContext.Provider value="dark"> <ThemedComponent /> </ThemeContext.Provider> );
-
useReducer: Manages complex state logic, similar to Redux.Code
import React, { useReducer } from 'react'; const initialState = { count: 0 }; const reducer = (state, action) => { switch (action.type) { case 'increment': return { count: state.count + 1 }; case 'decrement': return { count: state.count - 1 }; default: throw new Error(); } }; const Counter = () => { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>Increment</button> <button onClick={() => dispatch({ type: 'decrement' })}>Decrement</button> </div> ); };
-
useSelector: is a hook from the React-Redux library that allows you to extract data from the Redux store state.Code
import React from 'react'; import { useSelector } from 'react-redux'; const CounterDisplay = () => { const count = useSelector((state) => state.counter.value); return ( <div> <p>Count from Redux: {count}</p> </div> ); };
-
useCallback: Memoizes functions to prevent unnecessary re-renders.Code
import React, { useState, useCallback } from 'react'; const Button = React.memo(({ onClick }) => { console.log('Button rendered'); return <button onClick={onClick}>Click Me</button>; }); const ParentComponent = () => { const [count, setCount] = useState(0); const handleClick = useCallback(() => { setCount(count + 1); }, [count]); // Only recreate the function if count changes return ( <div> <p>Count: {count}</p> <Button onClick={handleClick} /> </div> ); }; const UserDetails = ({user, onEdit}) =>{
const {title, full_name, profile_img} = user;
return (
)
}
export default React.memo(UserDetails) ```
</p>
</details>
**[⬆ Back to Top](#table-of-contents)**
-
forwardRefis a React function that allows you to pass a ref through a component to one of its children, enabling parent components to directly interact with the child’s DOM node. -
Custom hooks are functions that allow you to extract and reuse stateful logic across multiple components. They can use built-in hooks and can be shared easily among different components.
import { useState } from 'react'; // Custom hook const useCounter = (initialValue = 0) => { const [count, setCount] = useState(initialValue); const increment = () => setCount(count + 1); const decrement = () => setCount(count - 1); const reset = () => setCount(initialValue); return { count, increment, decrement, reset }; }; // Component using the custom hook const Counter = () => { const { count, increment, decrement, reset } = useCounter(0); return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> <button onClick={decrement}>Decrement</button> <button onClick={reset}>Reset</button> </div> ); }; export default Counter;
-
We can create a function that uses
Promise.allto handle multiple Axios GET requests simultaneously.example:
import axios from 'axios'; const fetchMultipleRequests = async (urls) => { try { const requests = urls.map(url => axios.get(url)); const responses = await Promise.all(requests); return responses.map(response => response.data); } catch (error) { console.error('Error fetching data', error); throw error; } };
Given a plain React component with no lifecycle customizations, when does render get called? Select the best option: A. When this.setState is called B. When the component's parent is re-rendered C. When the component's props changes D. A and B E. All of the above