# React Cheat Sheet
## Table of Contents
1. [Introduction](#introduction)
2. [Creating a React App](#creating-a-react-app)
3. [JSX](#jsx)
4. [Components](#components)
- [Functional Components](#functional-components)
- [Class Components](#class-components)
5. [Props](#props)
6. [State](#state)
7. [Lifecycle Methods](#lifecycle-methods)
8. [Event Handling](#event-handling)
9. [Conditional Rendering](#conditional-rendering)
10. [Lists and Keys](#lists-and-keys)
11. [Forms](#forms)
12. [Hooks](#hooks)
- [useState](#usestate)
- [useEffect](#useeffect)
- [useContext](#usecontext)
13. [Context API](#context-api)
14. [React Router](#react-router)
15. [Redux](#redux)
16. [Fetching Data](#fetching-data)
17. [Error Boundaries](#error-boundaries)
18. [Refs](#refs)
19. [Portals](#portals)
20. [Fragments](#fragments)
21. [Higher-Order Components](#higher-order-components)
22. [Code Splitting](#code-splitting)
23. [React Developer Tools](#react-developer-tools)
24. [Deployment](#deployment)
## Introduction
React is a JavaScript library for building user interfaces. It allows developers to create large web
applications that can update and render efficiently in response to data changes.
## Creating a React App
```bash
npx create-react-app my-app
cd my-app
npm start
```
## JSX
```jsx
const element = <h1>Hello, world!</h1>;
```
## Components
### Functional Components
```jsx
function Greeting(props) {
return <h1>Hello, {[Link]}!</h1>;
}
```
### Class Components
```jsx
class Greeting extends [Link] {
render() {
return <h1>Hello, {[Link]}!</h1>;
}
}
```
## Props
```jsx
function Welcome(props) {
return <h1>Hello, {[Link]}</h1>;
}
<Welcome name="Sara" />
```
## State
```jsx
class Counter extends [Link] {
constructor(props) {
super(props);
[Link] = { count: 0 };
}
increment = () => {
[Link]({ count: [Link] + 1 });
};
render() {
return (
<div>
<p>Count: {[Link]}</p>
<button onClick={[Link]}>Increment</button>
</div>
);
}
}
```
## Lifecycle Methods
```jsx
class MyComponent extends [Link] {
componentDidMount() {
// Runs after the component is mounted
}
componentDidUpdate(prevProps, prevState) {
// Runs after the component updates
}
componentWillUnmount() {
// Runs before the component is unmounted
}
render() {
return <div>Hello</div>;
}
}
```
## Event Handling
```jsx
function ClickButton() {
const handleClick = () => {
alert('Button clicked!');
};
return <button onClick={handleClick}>Click Me</button>;
}
```
## Conditional Rendering
```jsx
function Greeting(props) {
if ([Link]) {
return <h1>Welcome back!</h1>;
}
return <h1>Please sign up.</h1>;
}
```
## Lists and Keys
```jsx
function NumberList(props) {
const numbers = [Link];
const listItems = [Link]((number) =>
<li key={[Link]()}>{number}</li>
);
return <ul>{listItems}</ul>;
}
```
## Forms
```jsx
class NameForm extends [Link] {
constructor(props) {
super(props);
[Link] = { value: '' };
[Link] = [Link](this);
[Link] = [Link](this);
}
handleChange(event) {
[Link]({ value: [Link] });
}
handleSubmit(event) {
alert('A name was submitted: ' + [Link]);
[Link]();
}
render() {
return (
<form onSubmit={[Link]}>
<label>
Name:
<input type="text" value={[Link]} onChange={[Link]} />
</label>
<input type="submit" value="Submit" />
</form>
);
}
}
```
## Hooks
### useState
```jsx
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
```
### useEffect
```jsx
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
[Link] = `You clicked ${count} times`;
}, [count]);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>Click me</button>
</div>
);
}
```
### useContext
```jsx
const MyContext = [Link]();
function MyComponent() {
const value = useContext(MyContext);
return <div>{value}</div>;
}
```
## Context API
```jsx
const MyContext = [Link]();
class MyProvider extends [Link] {
state = { value: 'Hello' };
render() {
return (
<[Link] value={[Link]}>
{[Link]}
</[Link]>
);
}
}
function MyComponent() {
return (
<[Link]>
{value => <div>{value}</div>}
</[Link]>
);
}
```
## React Router
```jsx
import { BrowserRouter as Router, Route, Switch, Link } from 'react-router-dom';
function App() {
return (
<Router>
<div>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Switch>
<Route path="/about">
<About />
</Route>
<Route path="/">
<Home />
</Route>
</Switch>
</div>
</Router>
);
}
```
## Redux
```bash
npm install redux react-redux
```
### Store
```jsx
import { createStore } from 'redux';
const initialState = { count: 0 };
function reducer(state = initialState, action) {
switch ([Link]) {
case 'INCREMENT':
return { count: [Link] + 1 };
default:
return state;
}
}
const store = createStore(reducer);
```
### Actions
```jsx
const increment = () => ({ type: 'INCREMENT' });
```
### Dispatch
```jsx
[Link](increment());
```
### React-Redux
```jsx
import { Provider, connect } from 'react-redux';
function App(props) {
return (
<div>
<p>Count: {[Link]}</p>
<button onClick={[Link]}>Increment</button>
</div>
);
}
const mapStateToProps = state => ({ count: [Link] });
const mapDispatchToProps = { increment };
const ConnectedApp = connect(mapStateToProps, mapDispatchToProps)(App);
function Root() {
return (
<Provider store={store}>
<ConnectedApp />
</Provider>
);
}
```
## Fetching Data
```jsx
import React, { useState, useEffect } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('[Link]
.then(response => [Link]())
.then(data => setData(data));
}, []);
return (
<div>
{data ? <p>{data}</p> : <p>Loading...</p>}
</div>
);
}
```
## Error Boundaries
```jsx
class ErrorBoundary extends [Link] {
constructor(props) {
super(props);
[Link] = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error
}
render() {
if ([Link]) {
return <h1>Something went wrong.</h1>;
}
return [Link];
}
}
```
## Refs
```jsx
class MyComponent extends [Link] {
constructor(props) {
super(props);
[Link] = [Link]();
}
render() {
return <div ref={[Link]}>Hello</div>;
}
}
```
## Portals
```jsx
import ReactDOM from 'react-dom';
function MyPortal() {
return [Link](
<div>Portal Content</div>,
[Link]('portal-root')
);
}
```
## Fragments
```jsx
function FragmentExample() {
return (
<>
<h1>Hello</h1>
<p>World</p>
</>
);
}
```
## Higher-Order Components
```jsx
function withExtraProp(Component) {
return function EnhancedComponent(props) {
return <Component {...props} extraProp="extra" />;
};
}
```
## Code Splitting
```jsx
import React, { Suspense } from 'react';
const OtherComponent = [Link](() => import('./OtherComponent'));
function MyComponent() {
return (
<Suspense fallback={<div>Loading...</div>}>
<OtherComponent />
</Suspense>
);
}
```
## React Developer Tools
Install the React Developer Tools extension for Chrome or Firefox to debug React applications.
## Deployment
```bash
npm run build
```
Deploy the contents of the `build` folder to your web server.