Preparing for a React.js interview requires a solid understanding of core concepts, best practices, and real-world applications. This tutorial will walk you through the essential topics you need to master, along with code examples and explanations.
React is a component-based library. A component is a reusable piece of UI that can be composed to build complex user interfaces.
// Example of a functional component
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
JSX (JavaScript XML) allows you to write HTML-like syntax in JavaScript. It gets compiled into React.createElement() calls.
// Example of JSX
const element = (
<div>
<h1>Hello!</h1>
<p>Welcome to React.</p>
</div>
);
Props are read-only properties passed to components, while state is mutable data that can change over time.
// Example of using props and state
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
incrementCount = () => {
this.setState({ count: this.state.count + 1 });
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
The Context API allows you to pass data through the component tree without having to pass props down manually at every level.
// Example of using Context API
const MyContext = React.createContext();
function ParentComponent() {
return (
<MyContext.Provider value="Hello from context">
<ChildComponent />
</MyContext.Provider>
);
}
function ChildComponent() {
const value = useContext(MyContext);
return <p>{value}</p>;
}
Hooks are functions that let you "hook into" React state and lifecycle features from function components.
// Example of using hooks
import { useState, useEffect } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds + 1);
}, 1000);
return () => clearInterval(interval);
}, [seconds]);
return <p>Time: {seconds} seconds</p>;
}
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
// Example of using error boundaries
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error information to an error reporting service
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Memoization is a technique used to optimize performance by caching the results of expensive function calls.
// Example of using memoization with React.memo
import { memo } from 'react';
const MyComponent = memo(function MyComponent({ prop }) {
// Component implementation
});
Lazy loading allows you to split your code into smaller chunks and load them on demand, improving the initial load time.
// Example of lazy loading components
import React, { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
Redux is a predictable state container for JavaScript apps. It helps manage the application's state in a centralized way.
// Example of using Redux
import { createStore } from 'redux';
function reducer(state = { count: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
default:
return state;
}
}
const store = createStore(reducer);
store.dispatch({ type: 'INCREMENT' });
console.log(store.getState()); // { count: 1 }
Jest is a testing framework, while React Testing Library provides utilities that encourage good testing practices.
// Example of using Jest and React Testing Library
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
Code splitting is a feature of Webpack that allows you to split your code into various bundles which can then be loaded on demand or in parallel.
// Example of code splitting with React.lazy
import { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
Ensure your React components are accessible by following best practices such as using semantic HTML, providing alt text for images, and ensuring keyboard navigation.
// Example of accessible button component
function Button({ onClick, children }) {
return (
<button onClick={onClick} aria-label="Click me">
{children}
</button>
);
}
By mastering these topics and practicing with real-world examples, you'll be well-prepared for a React.js interview. Good luck!