React is an open-source JavaScript library used to create user interfaces in a declarative and efficient way. It is a component-based front-end library responsible only for the view layer of a Model View Controller (MVC) architecture. React is used to create modular user interfaces and promotes the development of reusable UI components that display dynamic data.

React Cheat Sheet
The react cheat sheet provides you simple and quick references to commonly used react methods. This single page contains all the important concepts and features of react required for performing all the basic tasks in React. It’s a great resource for both beginners and experienced developers to quickly look up React essentials.
Basic Setup
Follow the below steps to create a boilerplate
Step 1: Create the application using the command
npx create-react-app <<Project_Name>>
Step 2: Navigate to the folder using the command
cd <<Project_Name>>
Step 3: Open the App.js file and write the below code
JavaScript
// App.js
import React from 'react';
import './App.css';
export default function App() {
return (
<div >
Hello Geeks
Lets start learning React
</div>
)
}
JSX
JSX stands for JavaScript XML. JSX is basically a syntax extension of JavaScript. It helps us to write HTML in JavaScript and forms the basis of React Development. Using JSX is not compulsory but it is highly recommended for programming in React as it makes the development process easier as the code becomes easy to write and read.
Sample JSX code:
const ele = <h1>This is sample JSX</h1>;
React Elements
React elements are different from DOM elements as React elements are simple JavaScript objects and are efficient to create. React elements are the building blocks of any React app and should not be confused with React components.
React Element | Description | Syntax |
---|
Class Element Attributes | Passes attributes to an element. The major change is that class is changed to className | <div className= "exampleclass"></div> |
Style Element Attributes | Adds custom styling. We have to pass values in double parenthesis like {{}} | <div style= {{styleName: Value}}</div> |
Fragments | Used to create single parent component | <>//Other Components</> |
ReactJS Import and Export
In ReactJS we use importing and exporting to import already created modules and export our own components and modules rescpectively
Type of Import/Export | Description | Syntax |
---|
Importing Default exports | imports the default export from modules | import MOD_NAME from "PATH" |
Importing Named Values | imports the named export from modules | import {NAME} from "PATH" |
Multiple imports | Used to import multiple modules can be user defined of npm packages | import MOD_NAME, {NAME} from "PATH" |
Default Exports | Creates one default export. Each component can have onne default export | export default MOD_NAME |
Named Exports | Creates Named Exports when there are multiple components in a single module | export default {NAME} |
Multiple Exports | Exports mulitple named components | export default {NAME1, NAME2} |
React Components
A Component is one of the core building blocks of React. Components in React basically return a piece of JSX code that tells what should be rendered on the screen.
Component | Description | Syntax |
---|
Functional | Simple JS functions and are stateless | function demoComponent() { return (<> // CODE </>); } |
Class-based | Uses JS classes to create stateful components | class Democomponent extends React.Component { render() { return <>//CODE</>; } } |
Nested | Creates component inside another component | function demoComponent() { return (<> <Another_Component/> </>); } |
JavaScript
// Functional Component
export default function App() {
return (
<div >
Hello Geeks
Lets start learning React
</div>
)
}
// Class Component with nesting
class Example extends React.Component {
render() {
return (
<div >
<App/>
Hello Geeks
Lets start learning React
</div>
)
}
}
Managing Data Inside and Outside Components(State and props)
Property | Description | Syntax |
---|
props | Passes data between components and is read-only. Mainly used in functional components | // Passing <Comp prop_name="VAL"/> //Accessing <Comp>{this.props.prop_name}</Comp> |
state | Manages data inside a component and is mutable. Used with class components | constructor(props) { super(props); this.state = { var: value, }; } |
setState | Updates the value of a state using callback function. it is an asynchronous function call | this.setState((prevState)=>({ // CODE LOGIC })) |
JavaScript
const App = () => {
const message = "Hello from functional component!";
return (
<div>
<ClassComponent message={message} />
</div>
);
};
class ClassComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: this.props.message
};
}
render() {
return (
<div>
<h2>Class Component</h2>
<p>State from prop: {this.state.message}</p>
</div>
);
}
}
Lifecycle of Components
The lifecycle methods in ReactJS are used to control the components at different stages from initialization till unmounting.
Mounting Phase methods
Updating Phase Methods
Method | Description | Syntax |
---|
componentDidUpdate | Invokes after component is updated | componentDidUpdate(prevProp, prevState, snap) |
shouldComponentUpdate | Used to avoid call in while re-rendering | shouldComponentUpdate(newProp. newState) |
render | Render component after update | render() |
JavaScript
import React from 'react';
import ReactDOM from 'react-dom';
class Test extends React.Component {
constructor(props) {
super(props);
this.state = { hello: "World!" };
}
componentWillMount() {
console.log("componentWillMount()");
}
componentDidMount() {
console.log("componentDidMount()");
}
changeState() {
this.setState({ hello: "Geek!" });
}
render() {
return (
<div>
<h1>GeeksForGeeks.org, Hello{this.state.hello}</h1>
<h2>
<a onClick={this.changeState.bind(this)}>Press Here!</a>
</h2>
</div>);
}
shouldComponentUpdate(nextProps, nextState) {
console.log("shouldComponentUpdate()");
return true;
}
componentWillUpdate() {
console.log("componentWillUpdate()");
}
componentDidUpdate() {
console.log("componentDidUpdate()");
}
}
ReactDOM.render(
<Test />,
document.getElementById('root'));
Conditional Rendering
In React, conditional rendering is used to render components based on some conditions. If the condition is satisfied then only the component will be rendered. This helps in encapsulation as the user is allowed to see only the desired component and nothing else.
Type | Description | Syntax |
---|
if-else | Component is rendered using if-else block | if (condition) { return <COMP1 />; }else{ return <COMP2/>; } |
Logical && Operator | Used for showing/hiding single component based on condition | {condition && <Component/>} |
Ternary Operator | Component is rendered using if-else block | {Condition ? <COMP1/> : <COMP2/> } |
JavaScript
// Conditional Rendering Using if-else
import React from 'react';
import ReactDOM from 'react-dom';
// Example Component
function Example(props)
{
if(!props.toDisplay)
return null;
else
return <h1>Component is rendered</h1>;
}
ReactDOM.render(
<div>
<Example toDisplay = {true} />
<Example toDisplay = {false} />
</div>,
document.getElementById('root')
);
JavaScript
// Conditional rendering using ternary operator
import React from 'react';
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoggedIn: true,
};
}
render() {
const { isLoggedIn } = this.state;
return (
<div>
<h1>Small Conditional Rendering Example</h1>
{isLoggedIn ? (
<p>Welcome, you are logged in!</p>
) : (
<p>Please log in to access the content.</p>
)}
</div>
);
}
}
export default Example;
JavaScript
// Conditional Rendering using && operator
import React from 'react';
import ReactDOM from 'react-dom';
// Example Component
function Example()
{
const counter = 5;
return(<div>
{
(counter==5) &&
<h1>Hello World!</h1>
}
</div>
);
}
ReactDOM.render(
<Example />,
document.getElementById('root')
);
React Lists
We can create lists in React in a similar manner as we do in regular JavaScript i.e. by storing the list in an array. In order to traverse a list we will use the map() function.
Keys are used in React to identify which items in the list are changed, updated, or deleted. Keys are used to give an identity to the elements in the lists. It is recommended to use a string as a key that uniquely identifies the items in the list.
Code Snippet:
const arr = [];
const listItems = numbers.map((number) =>
<li key={number.toString()}>
{number}
</li>
);
JavaScript
import React from 'react';
import ReactDOM from 'react-dom';
const numbers = [1,2,3,4,5];
const updatedNums = numbers.map((number)=>{
return <li>{number}</li>;
});
ReactDOM.render(
<ul>
{updatedNums}
</ul>,
document.getElementById('root')
);
React DOM Events
Similar to HTML events, React DOM events are used to perform events based on user inputs such as click, onChange, mouseOver etc
Method | Description | Syntax |
---|
Click | Triggers an event on click | <button onClick={func}>CONTENT</button> |
Change | Triggers when some change is detected in component | <input onChange={handleChange} /> |
Submit | Triggers an event when form is submitted | <form onSubmit={(e) => {//LOGIC}}></form> |
JavaScript
import React, { useState } from "react";
const App = () => {
// Counter is a state initialized to 0
const [counter, setCounter] = useState(0)
// Function is called everytime increment button is clicked
const handleClick1 = () => {
// Counter state is incremented
setCounter(counter + 1)
}
// Function is called everytime decrement button is clicked
const handleClick2 = () => {
// Counter state is decremented
setCounter(counter - 1)
}
return (
<div>
Counter App
<div style={{
fontSize: '120%',
position: 'relative',
top: '10vh',
}}>
{counter}
</div>
<div className="buttons">
<button onClick={handleClick1}>Increment</button>
<button onClick={handleClick2}>Decrement</button>
</div>
</div>
)
}
export default App
React Hooks
Hooks are used to give functional components an access to use the states and are used to manage side-effects in React. They were introduced React 16.8. They let developers use state and other React features without writing a class For example- State of a component It is important to note that hooks are not used inside the classes.
Hook | Description | Syntax |
---|
useState | Declares state variable inside a function | const [var, setVar] = useState(Val); |
useEffect | Handle side effect in React | useEffect(<FUNCTION>, <DEPENDECY>) |
useRef | Directly creates reference to DOM element | const refContainer = useRef(initialValue); |
useMemo | Returns a memoized value | const memVal = useMemo(function, arrayDependencies) |
JavaScript
import React, { useState } from 'react';
import ReactDOM from 'react-dom/client';
function App() {
const [click, setClick] = useState(0);
// using array destructuring here
// to assign initial value 0
// to click and a reference to the function
// that updates click to setClick
return (
<div>
<p>You clicked {click} times</p>
<button onClick={() => setClick(click + 1)}>
Click me
</button>
</div>
);
}
export default App;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
PropTypes
PropTypes in React are used to check the value of a prop which is passed into the component. These help in error hanling and are very useful in large scale applications.
Primitive Data Types
Type | Class/Syntax | Example |
---|
String | PropTypes.string | "Geeks" |
Object | PropType.object | {course: "DSA"} |
Number | PropType.number | 15, |
Boolean | PropType.bool | true |
Function | PropType.func | const GFG ={return "Hello"} |
Symbol | PropType.symbol | Symbol("symbole_here" |
Array Types
Type | Class/Syntax | Example |
---|
Array | PropTypes.array | [] |
Array of strings | PropTypes.arrayOf([type]) | [15,16,17] |
Array of numbers | PropTypes.oneOf([arr]) | ["Geeks", "For", "Geeks" |
Array of objects | PropTypes.oneOfType([types]) | PropTypes.instanceOf() |
Object Types
Type | Class/Syntax | Example |
---|
Object | PropTypes.object() | {course: "DSA"} |
Number Object | PropTypes.objectOf() | {id: 25} |
Object Shape | PropTypes.shape() | {course: PropTypes.string, price: PropTypes.number} |
Instance | PropTypes.objectOf() | new obj() |
JavaScript
import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom/client';
// Component
class ComponentExample extends React.Component{
render(){
return(
<div>
{/* printing all props */}
<h1>
{this.props.arrayProp}
<br />
{this.props.stringProp}
<br />
{this.props.numberProp}
<br />
{this.props.boolProp}
<br />
</h1>
</div>
);
}
}
// Validating prop types
ComponentExample.propTypes = {
arrayProp: PropTypes.array,
stringProp: PropTypes.string,
numberProp: PropTypes.number,
boolProp: PropTypes.bool,
}
// Creating default props
ComponentExample.defaultProps = {
arrayProp: ['Ram', 'Shyam', 'Raghav'],
stringProp: "GeeksforGeeks",
numberProp: "10",
boolProp: true,
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<ComponentExample />
</React.StrictMode>
);
Error Boundaries
Error Boundaries basically provide some sort of boundaries or checks on errors, They are React components that are used to handle JavaScript errors in their child component tree.
React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. It catches errors during rendering, in lifecycle methods, etc.
JavaScript
import React, { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
componentDidCatch(error, info) {
// Log the error to an error reporting service
console.error('Error:', error);
console.error('Info:', info);
this.setState({ hasError: true });
}
render() {
if (this.state.hasError) {
// Fallback UI when an error occurs
return <div>Something went wrong!</div>;
}
return this.props.children;
}
}
export default ErrorBoundary;
//Apply Error Boundary
import React from 'react';
import ErrorBoundary from './ErrorBoundary';
function App() {
return (
<ErrorBoundary>
<div>
{/* Your components here */}
</div>
</ErrorBoundary>
);
}
export default App;
This React Cheat Sheet gives you quick access to the most commonly used React concepts and methods. From setting up project to managing state and handling events, everything to build dynamic and responsive user interfaces with React.
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDOM is a core React package that provides methods to interact with the Document Object Model, or DOM. This package allows developers to access and modify the DOM. It is a package in React that provides DOM-specific methods that can be used at the top level of a web app to enable an efficient wa
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects