React has become one of the most sought-after technologies in web development. Whether you’re preparing for your first React interview or aiming to crack an advanced-level position, having a cheat sheet of essential concepts and examples can make all the difference. This article will explore the must-know concepts in React, ranging from foundational to expert levels, to help you ace your interview.
What is React, and Why is it So Popular?
React is a JavaScript library created by Facebook for building user interfaces. Its popularity stems from its component-based architecture, declarative programming style, and performance optimization capabilities through tools like the Virtual DOM. React’s ecosystem also supports robust development workflows with tools like React Router and state management libraries such as Redux and Context API.
How Do You Create a Basic React Component?
A React component is a building block of a React application. Components can be functional or class-based. Here's a simple example of both:
Functional Component:
function Greeting() { return <h1>Hello, World!</h1>; }
Class Component:
class Greeting extends React.Component { render() { return <h1>Hello, World!</h1>; } }
Functional components are preferred due to their simplicity and support for hooks.
What Are React Hooks?
Hooks are functions that let you use state and lifecycle methods in functional components. Here are three important hooks:
1. useState
for State Management:
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> ); }
2. useEffect
for Side Effects:
import React, { useEffect, useState } from 'react'; function Timer() { const [seconds, setSeconds] = useState(0); useEffect(() => { const interval = setInterval(() => { setSeconds((prev) => prev + 1); }, 1000); return () => clearInterval(interval); }, []); return <p>Seconds Elapsed: {seconds}</p>; }
3. useContext
for Context API:
import React, { createContext, useContext } from 'react'; const UserContext = createContext(); function DisplayName() { const user = useContext(UserContext); return <p>Username: {user.name}</p>; } function App() { return ( <UserContext.Provider value={{ name: 'John Doe' }}> <DisplayName /> </UserContext.Provider> ); }
What Are Props, and How Do You Use Them?
Props (short for properties) are the way to pass data between components in React. Props are immutable and allow parent components to control child components.
Example of Props:
function Welcome(props) { return <h1>Hello, {props.name}!</h1>; } function App() { return <Welcome name="Alice" />; }
Here, Welcome
receives name
as a prop and uses it in the JSX.
How Do You Handle State in React?
State is a mutable data structure used to control a component’s dynamic behavior. Functional components use useState
, while class components use this.state
and this.setState
.
Class Component State Example:
class Counter extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; } increment = () => { this.setState({ count: this.state.count + 1 }); }; render() { return ( <div> <p>Count: {this.state.count}</p> <button onClick={this.increment}>Increment</button> </div> ); } }
What Is JSX, and How Does It Work?
JSX stands for JavaScript XML and is a syntax extension that allows mixing HTML with JavaScript. Browsers don’t understand JSX directly, so it is transpiled by Babel into plain JavaScript.
JSX Example:
const element = <h1>Hello, World!</h1>; // Transpiles to: const element = React.createElement('h1', null, 'Hello, World!');
How Do You Optimize React Applications?
Optimizing React applications ensures faster rendering and better performance. Some techniques include:
1. Memoization with React.memo
:
const MemoizedComponent = React.memo(function MyComponent({ value }) { console.log('Rendered'); return <p>{value}</p>; });
2. Using useCallback
:
import React, { useCallback } from 'react'; function Button({ onClick }) { return <button onClick={onClick}>Click Me</button>; } function App() { const handleClick = useCallback(() => { console.log('Button Clicked'); }, []); return <Button onClick={handleClick} />; }
3. Lazy Loading Components:
import React, { Suspense, lazy } from 'react'; const LazyComponent = lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<p>Loading...</p>}> <LazyComponent /> </Suspense> ); }
What Are Higher-Order Components (HOCs)?
HOCs are functions that take a component and return a new component, enhancing the original component with additional functionality.
Example HOC:
function withLogging(WrappedComponent) { return function EnhancedComponent(props) { useEffect(() => { console.log('Component Mounted'); }, []); return <WrappedComponent {...props} />; }; }
How Does React Handle Forms?
React provides controlled and uncontrolled components for handling forms.
Controlled Component:
function Form() { const [value, setValue] = useState(''); const handleChange = (e) => setValue(e.target.value); return ( <input type="text" value={value} onChange={handleChange} /> ); }
Uncontrolled Component:
function UncontrolledForm() { const inputRef = React.useRef(); const handleSubmit = (e) => { e.preventDefault(); console.log(inputRef.current.value); }; return ( <form onSubmit={handleSubmit}> <input type="text" ref={inputRef} /> <button type="submit">Submit</button> </form> ); }
What Is the Difference Between Context API and Redux?
The Context API is a built-in state management solution for sharing data globally, while Redux is an external library offering more robust state management features.
Context API:
const ThemeContext = React.createContext('light'); function App() { return ( <ThemeContext.Provider value="dark"> <Child /> </ThemeContext.Provider> ); }
Redux:
import { createStore } from 'redux'; import { Provider, useSelector, useDispatch } from 'react-redux'; const reducer = (state = { count: 0 }, action) => { switch (action.type) { case 'INCREMENT': return { ...state, count: state.count + 1 }; default: return state; } }; const store = createStore(reducer); function Counter() { const count = useSelector((state) => state.count); const dispatch = useDispatch(); return ( <div> <p>Count: {count}</p> <button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button> </div> ); } function App() { return ( <Provider store={store}> <Counter /> </Provider> ); }
How Do You Test React Applications?
React testing often involves tools like Jest and React Testing Library.
Example:
import { render, fireEvent } from '@testing-library/react'; import Counter from './Counter'; test('increments counter', () => { const { getByText } = render(<Counter />); const button = getByText(/increment/i); fireEvent.click(button); expect(getByText(/count: 1/i)).toBeInTheDocument(); });
What Are React’s Lifecycle Methods?
Lifecycle methods are hooks in class components for managing a component’s lifecycle.
Example:
class MyComponent extends React.Component { componentDidMount() { console.log('Mounted'); } componentWillUnmount() { console.log('Unmounted'); } render() { return <p>Hello, World!</p>; } }
What Are the Best Practices for React Development?
- Use functional components and hooks.
- Optimize performance with memoization.
- Keep components small and reusable.
- Use PropTypes for type checking.
- Implement proper folder structure.
- Avoid inline functions in render methods.
By mastering these concepts and examples, you’ll be well-equipped to tackle React interviews with confidence.