Welcome to React! React is a JavaScript library for building user interfaces. It lets you build single-page applications with a component-based architecture.
React is a powerful tool for building modern web applications. It allows you to break down your UI into components that can be reused and maintained efficiently.
To get started with React, first install Node.js and create a new React app using the command npx create-react-app my-app
.
# Install React
npx create-react-app my-app
cd my-app
npm start
Upgrading React to the latest version is important for taking advantage of new features and performance improvements. Run npm update react react-dom
to upgrade your React app.
React uses ES6 features like arrow functions, classes, and destructuring to make the code cleaner and more readable. Here is an example:
class MyComponent extends React.Component {
render() {
const { name } = this.props;
return Hello, {name}
;
}
}
ES6 (ECMAScript 2015) introduced several new features to JavaScript that make working with React easier and more efficient. Below are some of the key ES6 features used in React development.
ES6 introduced classes, which are a syntactical sugar over JavaScript's prototype-based inheritance. Classes are used to create React components in a more readable and structured way.
class MyComponent extends React.Component {
render() {
return Hello, World!
;
}
}
Arrow functions provide a more concise syntax for writing functions. They also handle the `this` keyword differently, which is useful in React components for event handling and callbacks.
// Regular function
const sayHello = function() {
console.log("Hello");
};
// Arrow function
const sayHelloArrow = () => {
console.log("Hello");
};
ES6 introduced two new ways to declare variables: `let` and `const`. `let` allows block-scoped variables, while `const` is used for constants that should not be reassigned.
let name = "John"; // can be reassigned
const age = 30; // cannot be reassigned
name = "Doe"; // valid
// age = 31; // Error: Assignment to constant variable
ES6 introduced several new array methods that make manipulating arrays more convenient, such as `map()`, `filter()`, and `reduce()`.
const numbers = [1, 2, 3, 4];
// map example
const doubled = numbers.map(num => num * 2);
// filter example
const evenNumbers = numbers.filter(num => num % 2 === 0);
// reduce example
const sum = numbers.reduce((acc, num) => acc + num, 0);
Destructuring allows you to extract values from arrays or objects and assign them to variables in a concise way.
// Array Destructuring
const arr = [1, 2, 3];
const [a, b] = arr; // a = 1, b = 2
// Object Destructuring
const person = { name: "John", age: 30 };
const { name, age } = person; // name = "John", age = 30
The spread operator (`...`) allows you to expand arrays or objects into individual elements. It is useful for merging arrays or cloning objects.
// Array Spread
const numbers1 = [1, 2, 3];
const numbers2 = [...numbers1, 4, 5]; // [1, 2, 3, 4, 5]
// Object Spread
const person = { name: "John", age: 30 };
const updatedPerson = { ...person, age: 31 }; // { name: "John", age: 31 }
ES6 introduced a module system for importing and exporting code between files. You can use `import` and `export` to break your code into smaller, reusable pieces.
// Exporting from a file (math.js)
export const add = (a, b) => a + b;
// Importing in another file
import { add } from './math';
console.log(add(1, 2)); // 3
The ternary operator is a shorthand way of writing an `if-else` statement. It is often used in React for conditional rendering.
const age = 18;
const isAdult = age >= 18 ? "Adult" : "Minor";
console.log(isAdult); // "Adult"
React allows you to render HTML using JSX syntax, which looks like HTML but is actually JavaScript. Below is an example of rendering HTML in React:
const element = Hello, World!
;
ReactDOM.render(element, document.getElementById('root'));
JSX is a syntax extension for JavaScript. It looks like HTML but works within JavaScript. Here's an example of JSX:
const element = Hello, JSX!
;
ReactDOM.render(element, document.getElementById('root'));
Components are the building blocks of React applications. A component can be a function or a class that returns JSX to render UI elements.
function Welcome(props) {
return Hello, {props.name}
;
}
In React, a class component allows you to use features like state and lifecycle methods. Below is an example of a class component:
class Welcome extends React.Component {
constructor(props) {
super(props);
this.state = { name: 'John' };
}
render() {
return Hello, {this.state.name}
;
}
}
Props (short for properties) are used to pass data from one component to another in React. Props are read-only and cannot be modified by the child component.
function Greeting(props) {
return Hello, {props.name}!
;
}
React handles events using camelCase syntax. You can listen for events like clicks, key presses, etc., and trigger functions in response.
function handleClick() {
alert('Button clicked!');
}
function App() {
return ;
}
You can use JavaScript conditional statements inside JSX to render content based on certain conditions.
function Greeting(props) {
if (props.isLoggedIn) {
return Welcome back!
;
} else {
return Please sign in.
;
}
}
React allows you to render lists dynamically using the map()
method. It’s common to use lists for rendering multiple elements.
function List(props) {
const items = props.items;
return (
{items.map(item => - {item.name}
)}
);
}
Forms in React are handled using controlled components, where the form data is managed by the state of the component.
function Form() {
const [value, setValue] = React.useState('');
function handleChange(event) {
setValue(event.target.value);
}
function handleSubmit(event) {
alert('Form submitted with: ' + value);
event.preventDefault();
}
return (
);
}
React Router is used to handle routing in React applications. It enables you to navigate between different components or pages in your app.
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
function App() {
return (
);
}
React Memo is a higher-order component that prevents unnecessary re-rendering of components by memorizing the result of a render.
const MyComponent = React.memo(function MyComponent(props) {
return {props.name}
;
});
In React, you can apply CSS styles either by importing a separate CSS file or by using inline styles directly within the JSX.
import './App.css';
function App() {
return Hello, React!
;
}
React supports Sass for more advanced and maintainable styling. You can import Sass files into your React components.
import './App.scss';
function App() {
return Hello, React with Sass!
;
}
React hooks are functions that let you "hook into" React state and lifecycle features from function components. They allow you to use state, effects, context, refs, reducers, and more without needing to write a class component.
A hook is a special function in React that allows you to use state and other React features without writing a class component. Hooks are introduced in React 16.8 to allow function components to manage state, side effects, context, refs, etc.
function Counter() {
const [count, setCount] = useState(0);
return {count}
;
}
The useState
hook allows you to add state to function components. It returns an array with two elements: the current state value and a function to update it.
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
{count}
);
}
The useEffect
hook allows you to perform side effects in your function components. It runs after the render and can be used for things like data fetching, subscriptions, and manually changing the DOM.
import React, { useEffect, useState } from 'react';
function Timer() {
const [seconds, setSeconds] = useState(0);
useEffect(() => {
const timer = setInterval(() => setSeconds(s => s + 1), 1000);
return () => clearInterval(timer); // Cleanup
}, []); // Empty dependency array means it runs once when component mounts
return {seconds} seconds
;
}
The useContext
hook allows you to access values from a context directly in a function component without needing to wrap it in a Consumer
component.
import React, { useContext } from 'react';
const ThemeContext = React.createContext('light');
function ThemedComponent() {
const theme = useContext(ThemeContext);
return This is a {theme} themed component;
}
The useRef
hook is used to persist values between renders. It can also be used to reference DOM elements.
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef(null);
const focus = () => {
inputRef.current.focus();
};
return (
);
}
The useReducer
hook is an alternative to useState
that is preferable when the state logic is complex or involves multiple sub-values.
import React, { useReducer } from 'react';
function counterReducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
const [state, dispatch] = useReducer(counterReducer, { count: 0 });
return (
{state.count}
);
}
The useCallback
hook returns a memoized version of a callback function. This is useful when passing a callback to a component that relies on reference equality to prevent unnecessary renders.
import React, { useState, useCallback } from 'react';
function ParentComponent() {
const [count, setCount] = useState(0);
const memoizedCallback = useCallback(() => {
console.log('Memoized function');
}, [count]);
return (
{count}
);
}
The useMemo
hook returns a memoized value. It’s useful for expensive calculations that need to be recomputed only when necessary.
import React, { useMemo, useState } from 'react';
function ExpensiveCalculation({ num }) {
const result = useMemo(() => {
return num * 2; // expensive calculation
}, [num]);
return Result: {result}
;
}
function App() {
const [num, setNum] = useState(1);
return (
);
}
Custom hooks are JavaScript functions that can call other hooks to encapsulate logic and reuse it across different components.
import { useState } from 'react';
function useCounter(initialValue = 0) {
const [count, setCount] = useState(initialValue);
const increment = () => setCount(count + 1);
const decrement = () => setCount(count - 1);
return { count, increment, decrement };
}
function Counter() {
const { count, increment, decrement } = useCounter(10);
return (
{count}
);
}
React exercises are a great way to practice and enhance your understanding of React concepts. Below are some exercises that cover a wide range of React topics like components, state, hooks, and routing.
// Example Exercise 1: Creating a simple counter
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
{count}
);
}
The React compiler refers to the tool that transforms JSX code into JavaScript that browsers can understand. React typically uses Babel for this transformation.
// JSX code that gets compiled into JavaScript
const element = Hello, world!
;
ReactDOM.render(element, document.getElementById('root'));
Ensure that Babel is set up in your project for JSX to be properly compiled and run in the browser.
Test your knowledge of React with this interactive quiz. Answer the following questions:
Answer these questions to assess your understanding of React basics, and move on to more advanced concepts like hooks and state management.
Setting up a React development server is essential for running and testing your React applications locally. You can use the Create React App tool to set up the development environment quickly.
// Install Create React App globally
npm install -g create-react-app
// Create a new React app
create-react-app my-app
// Navigate into your app's directory and start the server
cd my-app
npm start
Once the server is running, you can view your app in the browser at http://localhost:3000
.
Prepare for React job interviews by reviewing common questions and concepts:
Reviewing these concepts will help you be ready for technical interviews involving React.
After completing the React tutorials and exercises, you can earn a React certificate. This certificate can be used to showcase your skills in React development.
There are several platforms offering React certification, such as:
Make sure to complete the required courses, pass quizzes, and build projects to earn your certificate.
The Context API allows you to share values like state, functions, etc., across the entire component tree without needing to explicitly pass props at each level.
import React, { createContext, useContext } from 'react';
const MyContext = createContext();
const ParentComponent = () => {
return (
);
};
const ChildComponent = () => {
const value = useContext(MyContext);
return {value}
;
};
export default ParentComponent;
Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI.
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return Something went wrong!
;
}
return this.props.children;
}
}
export default ErrorBoundary;
React Suspense is a feature that lets you wait for some code to load asynchronously before rendering a component.
import React, { Suspense, lazy } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => {
return (
Loading...}>
);
};
export default App;
React.lazy() allows you to dynamically import a component and only load it when needed, which improves the performance of your app by splitting the code.
import React, { lazy, Suspense } from 'react';
const OtherComponent = lazy(() => import('./OtherComponent'));
const App = () => {
return (
Loading...}>
);
};
export default App;
Concurrent Mode is an experimental feature that helps React apps stay responsive and gracefully adjust to the user’s device capabilities and network speed.
import React, { Suspense, lazy } from 'react';
import { createRoot } from 'react-dom';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => (
Loading...}>
);
const root = createRoot(document.getElementById('root'));
root.render();
React Testing Library is a set of utilities that helps you test your React components with a focus on the behavior and rendering, rather than the implementation details.
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render();
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
PropTypes is a tool for type-checking props in React. It ensures that the components receive props of the correct data type.
import PropTypes from 'prop-types';
const MyComponent = ({ name, age }) => {
return {name} is {age} years old.
;
};
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number.isRequired,
};
export default MyComponent;
Server-side rendering is a technique used in React to render components on the server before sending the HTML to the browser, which helps with SEO and performance.
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import App from './App';
const html = ReactDOMServer.renderToString();
console.log(html);
SSG allows you to generate static HTML pages at build time, making them faster to load and easier to serve to users.
import React from 'react';
const Page = ({ data }) => {data};
export async function getStaticProps() {
const data = 'Static Content';
return { props: { data } };
}
export default Page;
React Native allows you to build mobile apps using JavaScript and React, but with native components and APIs for iOS and Android.
import React from 'react';
import { View, Text } from 'react-native';
const App = () => {
return (
Hello, React Native!
);
};
export default App;
Optimizing the use of React Context API to prevent unnecessary re-renders, especially in large applications.
import React, { createContext, useState, useContext } from 'react';
const MyContext = createContext();
const Parent = () => {
const [value, setValue] = useState(0);
return (
);
};
const Child = () => {
const { value, setValue } = useContext(MyContext);
return (
{value}
);
};
export default Parent;
Redux is a state management library that can be used with React to manage the global state of an app, especially for larger applications.
import React from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
const initialState = { count: 0 };
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
default:
return state;
}
};
const store = createStore(reducer);
const App = () => {
return (
React-Redux Example
);
};
export default App;
Custom hooks allow you to reuse stateful logic across components in a clean way.
import { useState, useEffect } from 'react';
const useWindowWidth = () => {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
};
export default useWindowWidth;
A Higher-Order Component (HOC) is a function that takes a component and returns a new component with additional props.
import React from 'react';
const withBorder = (WrappedComponent) => {
return (props) => (
);
};
const Button = () => ;
export default withBorder(Button);