Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML Cheat Sheet
  • CSS Cheat Sheet
  • JS Cheat Sheet
  • Bootstrap Cheat Sheet
  • jQuery Cheat Sheet
  • Angular Cheat Sheet
  • SDE Sheet
  • Facebook SDE Sheet
  • Amazon SDE Sheet
  • Apple SDE Sheet
  • Netflix SDE Sheet
  • Google SDE Sheet
  • Wipro SDE Sheet
  • Infosys SDE Sheet
  • TCS SDE Sheet
  • Cognizant SDE Sheet
  • HCL SDE Sheet
  • Mass Recruiters Sheet
  • Product-Based Coding Sheet
  • Company-Wise Practice Sheet
  • Love Babbar Sheet
Open In App
Next Article:
HTML Complete Guide – A to Z HTML Concepts
Next article icon

React Cheat Sheet

Last Updated : 17 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

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.

Table of Content

  • Basic Setup
  • JSX
  • React Elements
  • ReactJS Import and Export
  • React Components
  • Lifecycle of Components
  • Conditional Rendering
  • React Lists
  • React DOM Events
  • React Hooks
  • PropTypes

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 ElementDescriptionSyntax
Class Element AttributesPasses attributes to an element. The major change is that class is changed to className<div className= "exampleclass"></div>
Style Element AttributesAdds custom styling. We have to pass values in double parenthesis like {{}}<div style= {{styleName: Value}}</div>
FragmentsUsed 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/ExportDescriptionSyntax
Importing Default exportsimports the default export from modulesimport MOD_NAME from "PATH"
Importing Named Valuesimports the named export from modulesimport {NAME} from "PATH"
Multiple importsUsed to import multiple modules can be user defined of npm packagesimport MOD_NAME, {NAME} from "PATH"
Default ExportsCreates one default export. Each component can have onne default exportexport default MOD_NAME
Named ExportsCreates Named Exports when there are multiple components in a single moduleexport default {NAME}
Multiple ExportsExports 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.

ComponentDescriptionSyntax
FunctionalSimple JS functions and are statelessfunction demoComponent() {
   return (<>
               // CODE
           </>);
}
Class-basedUses JS classes to create stateful componentsclass Democomponent extends React.Component {
   render() {
       return <>//CODE</>;
   }
}
NestedCreates component inside another componentfunction 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)

PropertyDescriptionSyntax
propsPasses data between components and is read-only. Mainly used in functional components

// Passing
<Comp prop_name="VAL"/>

//Accessing
<Comp>{this.props.prop_name}</Comp>

stateManages data inside a component and is mutable. Used with class componentsconstructor(props) {
       super(props);
       this.state = {
           var: value,
       };
 }
setStateUpdates the value of a state using callback function. it is an asynchronous function callthis.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

MethodDescriptionSyntax
constructorRuns before component renderingconstructor(props){}
renderUsed to render the componentrender()
componentDidMountRuns after component is renderedcomponentDidMount()
componentWillUnmountRuns before a component is removed from DOMcomoponentWillUnmount()
componentDidCatchUsed to catch errors in componentcomponentDidCatch()

Updating Phase Methods

MethodDescriptionSyntax
componentDidUpdateInvokes after component is updatedcomponentDidUpdate(prevProp, prevState, snap)
shouldComponentUpdateUsed to avoid call in while re-renderingshouldComponentUpdate(newProp. newState)
renderRender component after updaterender()
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.

TypeDescriptionSyntax
if-elseComponent is rendered using if-else blockif (condition) {
    return <COMP1 />;
}else{
    return <COMP2/>;
}
Logical && OperatorUsed for showing/hiding single component based on condition{condition && <Component/>}
Ternary OperatorComponent 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

MethodDescriptionSyntax
ClickTriggers an event on click<button onClick={func}>CONTENT</button>
ChangeTriggers when some change is detected in component <input onChange={handleChange} />
SubmitTriggers 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.

HookDescriptionSyntax
useStateDeclares state variable inside a functionconst [var, setVar] = useState(Val);
useEffectHandle side effect in ReactuseEffect(<FUNCTION>, <DEPENDECY>)
useRefDirectly creates reference to DOM elementconst refContainer = useRef(initialValue);
useMemoReturns a memoized valueconst 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 

TypeClass/SyntaxExample
StringPropTypes.string"Geeks"
ObjectPropType.object{course: "DSA"}
NumberPropType.number15,
BooleanPropType.booltrue
FunctionPropType.funcconst GFG ={return "Hello"}
SymbolPropType.symbolSymbol("symbole_here"

Array Types

TypeClass/SyntaxExample
ArrayPropTypes.array[]
Array of stringsPropTypes.arrayOf([type])[15,16,17]
Array of numbersPropTypes.oneOf([arr])["Geeks", "For", "Geeks"
Array of objectsPropTypes.oneOfType([types])PropTypes.instanceOf()

Object Types

TypeClass/SyntaxExample
ObjectPropTypes.object(){course: "DSA"}
Number ObjectPropTypes.objectOf(){id: 25}
Object ShapePropTypes.shape()

{course: PropTypes.string,
price: PropTypes.number}

InstancePropTypes.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.


Next Article
HTML Complete Guide – A to Z HTML Concepts

K

kartik
Improve
Article Tags :
  • Web Technologies
  • ReactJS
  • GFG Sheets
  • Web-Dev Sheet

Similar Reads

    HTML Cheat Sheet
    HTML (HyperText Markup Language) serves as the foundational framework for web pages, structuring content like text, images, and videos. HTML forms the backbone of every web page, defining its structure, content, and interactions. Its enduring relevance lies in its universal adoption across web devel
    15+ min read
    CSS Cheat Sheet
    What is CSS? CSS i.e. Cascading Style Sheets is a stylesheet language used to describe the presentation of a document written in a markup language such as HTML, XML, etc. CSS enhances the look and feel of the webpage by describing how elements should be rendered on screen or in other media. What is
    13 min read
    JavaScript Cheat Sheet
    JavaScript is a lightweight, open, and cross-platform programming language. It is omnipresent in modern development and is used by programmers across the world to create dynamic and interactive web content like applications and browsersJavaScript (JS) is a versatile, high-level programming language
    15+ min read
    jQuery Cheat Sheet
    What is jQuery?jQuery is an open-source, feature-rich JavaScript library, designed to simplify the HTML document traversal and manipulation, event handling, animation, and Ajax with an easy-to-use API that supports the multiple browsers. It makes the easy interaction between the HTML & CSS docum
    15+ min read
    Angular Cheat Sheet
    Angular is a client-side TypeScript-based, front-end web framework developed by the Angular Team at Google, that is mainly used to develop scalable single-page web applications(SPAs) for mobile & desktop. Angular is a great, reusable UI (User Interface) library for developers that helps in build
    15+ min read
    Bootstrap Cheat Sheet
    Bootstrap is a free, open-source, potent CSS framework and toolkit used to create modern and responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. Nowadays, websites are perfect for all browsers and all
    15+ min read
    ReactJS Cheat Sheet
    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
    9 min read
    HTML Complete Guide
    What is HTML ? HTML stands for Hypertext Markup Language. It is a standard markup language used to design the documents displayed in the browsers as a web page. This language is used to annotate (make notes for the computer) text so that a machine can understand it and manipulate text accordingly. M
    7 min read
    CSS Complete Guide
    What is CSS ?CSS stands for "Cascading Style Sheet". It is used to style HTML Documents. CSS simplifies the process of making web pages presentable. It describes how web pages should look it prescribes colors, fonts, spacing, and much more.CSS Complete GuideWhat is CSS Complete Guide ?CSS Complete G
    4 min read
    JavaScript Complete Guide
    JavaScript is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for web pages. Some of the key features of JavaScript are:Lightweight and Fast: JavaScript is a lightweight programming language that runs quickly i
    6 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences