React JS Cheat Sheet

React Js Cheat Sheet : Do You Really Need It? This Will Help You Decide!

React is a JavaScript library for building user interfaces. This guide targets React v15 to v16. React allows developers to create large web applications that can change data, without reloading the page. The main purpose of React is to be fast, scalable, and simple. It works only on user interfaces in the application. It might seem overwhelming for a beginner to learn the React framework. After all, it has gone through a lot of changes since it was first released around 2013. Here’s a React JS cheat sheetnot a full tutorial but a simple-to-understand and concise overview on what it takes to learn React basics.

I’ve put together a super helpful cheat sheet to give you a complete overview of all of the React concepts you need to know in 2022.

What is React?

ReactJs is JavaScript library designed to create single-page applications with reusable UI components.

React stores the information DOM by creating a virtual DOM in its memory. Before it renders the DOM nodes onto the browser, it checks for changes between its past and present virtual DOM. If there’s a change (i.e. some text content updated), it will update its virtual DOM and then renders to the real DOM on the browser. See diagram below for visualization.

React Components

Components are one of the building blocks of a React App. They are basically React functions that returns an HTML element. Think of them as a large HTML blocks of code that independently does a certain function for the app. Like the navigation bar or the panels.

In React, all these components are structured as nodes in the Virtual DOM. It will render onto the browser according to how we specify them to look like.

import React from 'react'
import ReactDOM from 'react-dom'
class Hello extends React.Component {
  render () {
    return <div className='message-box'>
      Hello {this.props.name}
    </div>
  }
}
const el = document.body
ReactDOM.render(<Hello name='John' />, el)

Use the React.js jsfiddle to start hacking. (or the unofficial jsbin)

Import multiple exports

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
class Hello extends Component {
  ...
}

Properties

<Video fullscreen={true} autoplay={false} />
render () {
  this.props.fullscreen
  const { fullscreen, autoplay } = this.props
  ···
}
 
 
Use this.props to access properties passed to the component.

See: Properties

States

render () {
  this.state.username
  const { username } = this.state
  ···
}

Use states (this.state) to manage dynamic data.

With Babel you can use proposal-class-fields and get rid of constructor.

class Hello extends Component {
  state = { username: undefined };
  ...
}

Nesting

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return <div>
      <UserAvatar src={avatar} />
      <UserProfile username={username} />
    </div>
  }
}

As of React v16.2.0, fragments can be used to return multiple children without adding extra wrapping nodes to the DOM.

import React, {
  Component,
  Fragment
} from 'react'

class Info extends Component {
  render () {
    const { avatar, username } = this.props

    return (
      <Fragment>
        <UserAvatar src={avatar} />
        <UserProfile username={username} />
      </Fragment>
    )
  }
}

Children

class AlertBox extends Component {
  render () {
    return 
{this.props.children}
} }

Children are passed as the children property.

Defaults

Hello.defaultProps = {
  color: 'blue'
}

See: defaultProps

Setting default state

class Hello extends Component {
  constructor (props) {
    super(props)
    this.state = { visible: true }
  }
}

Set the default state in the constructor().

And without constructor using Babel with proposal-class-fields.

class Hello extends Component {
  state = { visible: true }
}

See: Setting the default state

Other components

Functional components

function MyComponent ({ name }) {
  return <div className='message-box'>
    Hello {name}
  </div>
}

Functional components have no state. Also, their props are passed as the first parameter to a function.

See: Function and Class Components

Pure components

import React, {PureComponent} from 'react'

class MessageBox extends PureComponent {
  ···
}

Performance-optimized version of React.Component. Doesn’t rerender if props/state hasn’t changed.

See: Pure components

Component API

this.forceUpdate()
this.setState({ ... })
this.setState(state => { ... })
this.state
this.props

These methods and properties are available for Component instances.

See: Component API

Lifecycle

Mounting

MethodDescription
constructor (props)Before rendering #
componentWillMount()Don’t use this #
render()Render #
componentDidMount()After rendering (DOM available) #
componentWillUnmount()Before DOM removal #
componentDidCatch()Catch errors (16+) #

Set initial the state on constructor().
Add DOM event handlers, timers (etc) on componentDidMount(), then remove them on componentWillUnmount().

Updating

MethodDescription
componentDidUpdate (prevProps, prevState, snapshot)Use setState() here, but remember to compare props
shouldComponentUpdate (newProps, newState)Skips render() if returns false
render()Render
componentDidUpdate (prevProps, prevState)Operate on the DOM here

Called when parents change properties and .setState(). These are not called for initial renders.

See: Component specs

Hooks (New)

State Hook

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

Hooks are a new addition in React 16.8.

See: Hooks at a Glance

Declaring multiple state variables

function ExampleWithManyStates() {
  // Declare multiple state variables!
  const [age, setAge] = useState(42);
  const [fruit, setFruit] = useState('banana');
  const [todos, setTodos] = useState([{ text: 'Learn Hooks' }]);
  // ...
}

Effect hook

import React, { useState, useEffect } from 'react';

function Example() {
  const [count, setCount] = useState(0);

  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    // Update the document title using the browser API
    document.title = `You clicked ${count} times`;
  }, [count]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMountcomponentDidUpdate, and componentWillUnmount combined.

By default, React runs the effects after every render — including the first render.

Building your own hooks

Define FriendStatus

import React, { useState, useEffect } from 'react';

function FriendStatus(props) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    function handleStatusChange(status) {
      setIsOnline(status.isOnline);
    }

    ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
    return () => {
      ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
    };
  }, [props.friend.id]);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

Effects may also optionally specify how to “clean up” after them by returning a function.

Use FriendStatus

function FriendStatus(props) {
  const isOnline = useFriendStatus(props.friend.id);

  if (isOnline === null) {
    return 'Loading...';
  }
  return isOnline ? 'Online' : 'Offline';
}

See: Building Your Own Hooks

Hooks API Reference

Also see: Hooks FAQ

Basic Hooks

HookDescription
useState(initialState)
useEffect(() => { … })
useContext(MyContext)value returned from React.createContext

Full details: Basic Hooks

Additional Hooks

HookDescription
useReducer(reducer, initialArg, init)
useCallback(() => { … })
useMemo(() => { … })
useRef(initialValue)
useImperativeHandle(ref, () => { … })
useLayoutEffectidentical to useEffect, but it fires synchronously after all DOM mutations
useDebugValue(value)display a label for custom hooks in React DevTools

Full details: Additional Hooks

DOM nodes

References

class MyComponent extends Component {
  render () {
    return <div>
      <input ref={el => this.input = el} />
    </div>
  }

  componentDidMount () {
    this.input.focus()
  }
}

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

class MyComponent extends Component {
  render () {
    <input type="text"
        value={this.state.value}
        onChange={event => this.onChange(event)} />
  }

  onChange (event) {
    this.setState({ value: event.target.value })
  }
}

Pass functions to attributes like onChange.

See: Events

Other features

Transferring props

<VideoPlayer src="video.mp4" />
class VideoPlayer extends Component {
  render () {
    return <VideoEmbed {...this.props} />
  }
}

Propagates src="..." down to the sub-component.

See Transferring props

Top-level API

React.createClass({ ... })
React.isValidElement(c)
ReactDOM.render(<Component />, domnode, [callback])
ReactDOM.unmountComponentAtNode(domnode)
ReactDOMServer.renderToString(<Component />)
ReactDOMServer.renderToStaticMarkup(<Component />)

There are more, but these are most common.

See: React top-level API

JSX patterns

Style shorthand

const style = { height: 10 }
return <div style={style}></div>
return <div style={{ margin: 0, padding: 0 }}></div>

See: Inline styles

Inner HTML

function markdownify() { return "<p>...</p>"; }
<div dangerouslySetInnerHTML={{__html: markdownify()}} />

See: Dangerously set innerHTML

Lists

class TodoList extends Component {
  render () {
    const { items } = this.props

    return <ul>
      {items.map(item =>
        <TodoItem item={item} key={item.key} />)}
    </ul>
  }
}

Always supply a key property.

Conditionals

<Fragment>
  {showMyComponent
    ? <MyComponent />
    : <OtherComponent />}
</Fragment>

Short-circuit evaluation

<Fragment>
  {showPopup && <Popup />}
  ...
</Fragment>

New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

render () {
  // Don't forget the keys!
  return [
    <li key="A">First item</li>,
    <li key="B">Second item</li>
  ]
}

Fragments

render () {
  return (
    <Fragment>
      <li>First item</li>
      <li>Second item</li>
    </Fragment>
  )
}

See: Fragments and strings

Returning strings

render() {
  return 'Look ma, no spans!';
}

You can return just a string.

See: Fragments and strings

Errors

class MyComponent extends Component {
  ···
  componentDidCatch (error, info) {
    this.setState({ error })
  }
}

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

render () {
  return React.createPortal(
    this.props.children,
    document.getElementById('menu')
  )
}

This renders this.props.children into any location in the DOM.

See: Portals

Hydration

const el = document.getElementById('app')
ReactDOM.hydrate(<App />, el)

Use ReactDOM.hydrate instead of using ReactDOM.render if you’re rendering over the output of ReactDOMServer.

See: Hydrate

Property validation

PropTypes

import PropTypes from 'prop-types'

See: Typechecking with PropTypes

KeyDescription
anyAnything

Basic

KeyDescription
string
number
funcFunction
boolTrue or false

Enum

KeyDescription
oneOf(any)Enum types
oneOfType(type array)Union

Array

KeyDescription
array
arrayOf(…)

Object

KeyDescription
object
objectOf(…)Object with values of a certain type
instanceOf(…)Instance of a class
shape(…)

Elements

KeyDescription
elementReact element
nodeDOM node

Required

KeyDescription
(···).isRequiredRequired

Basic types

MyComponent.propTypes = {
  email:      PropTypes.string,
  seats:      PropTypes.number,
  callback:   PropTypes.func,
  isClosed:   PropTypes.bool,
  any:        PropTypes.any
}

Required types

MyCo.propTypes = {
  name:  PropTypes.string.isRequired
}

Elements

MyCo.propTypes = {
  // React element
  element: PropTypes.element,

  // num, string, element, or an array of those
  node: PropTypes.node
}

Enumerables (oneOf)

MyCo.propTypes = {
  direction: PropTypes.oneOf([
    'left', 'right'
  ])
}

Arrays and objects

MyCo.propTypes = {
  list: PropTypes.array,
  ages: PropTypes.arrayOf(PropTypes.number),
  user: PropTypes.object,
  user: PropTypes.objectOf(PropTypes.number),
  message: PropTypes.instanceOf(Message)
}
MyCo.propTypes = {
  user: PropTypes.shape({
    name: PropTypes.string,
    age:  PropTypes.number
  })
}

Use .array[Of].object[Of].instanceOf.shape.

Custom validation

MyCo.propTypes = {
  customProp: (props, key, componentName) => {
    if (!/matchme/.test(props[key])) {
      return new Error('Validation failed!')
    }
  }
}

Wrapping Up

And that’s it for this React JS Cheat Sheet for beginners covering React basics. Ofcourse, it’s just concise article, so it cannot cover every single aspect of React. But, I hope it has been a great overview to help anyone embark on a React journey without feeling intimidated or too overwhelmed.

Thanks for reading and if you find this React JS cheat sheet helpful, please like and share this article around for more reach. Cheers!

Read More: How to Use Redux in Your ReactJS App in Just 10 Minutes?

Rahul Sharma

Rahul Sharma is a Founder of Logical IDEA and Bee Flirty. He is a Professional WP Developers, UX Designer, and Digital Marketing Expert. Previously, He Worked as a Digital Marketing Head for An eCommerce Startup. He Graduated with honors from Lovely Professional University with a Dual Degree in Information Technology.

24 comments

  • nimabi says:

    Thank you very much for sharing, I learned a lot from your article. Very cool. Thanks. nimabi

  • Qtbdfx says:

    costco canada cold and sinus antihistamine generic names best allergy medications over the counter

  • Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/zh-TC/join?ref=V2H9AFPY

  • tlovertonet says:

    Good day very cool web site!! Guy .. Excellent .. Amazing .. I will bookmark your web site and take the feeds additionally…I am satisfied to search out a lot of helpful information right here within the submit, we need work out extra techniques on this regard, thank you for sharing.

  • priscillawheuer says:

    Cramkey CIPM is a comprehensive investment portfolio management tool that empowers users to efficiently organize, analyze, and optimize their investments, providing insightful data for informed decision-making in the financial landscape.

  • Belowflowss says:

    Fantastic site Lots of helpful information here I am sending it to some friends ans additionally sharing in delicious And of course thanks for your effort

  • BlogSeventyy says:

    Hi Neat post There is a problem along with your website in internet explorer would test this IE still is the market chief and a good section of other folks will pass over your magnificent writing due to this problem

  • Mirlandss says:

    Somebody essentially lend a hand to make significantly articles Id state That is the very first time I frequented your website page and up to now I surprised with the research you made to make this actual submit amazing Wonderful task

  • Witronee says:

    Wonderful beat I wish to apprentice while you amend your web site how could i subscribe for a blog web site The account aided me a acceptable deal I had been a little bit acquainted of this your broadcast provided bright clear idea

  • minozz says:

    Attractive section of content I just stumbled upon your blog and in accession capital to assert that I get actually enjoyed account your blog posts Anyway I will be subscribing to your augment and even I achievement you access consistently fast

  • CloneBuzzz says:

    I loved as much as youll receive carried out right here The sketch is tasteful your authored material stylish nonetheless you command get bought an nervousness over that you wish be delivering the following unwell unquestionably come more formerly again since exactly the same nearly a lot often inside case you shield this hike

  • Blogfoloww says:

    Wow superb blog layout How long have you been blogging for you make blogging look easy The overall look of your site is magnificent as well as the content

  • BlogMerkk says:

    helloI really like your writing so a lot share we keep up a correspondence extra approximately your post on AOL I need an expert in this house to unravel my problem May be that is you Taking a look ahead to see you

  • Your point of view caught my eye and was very interesting. Thanks. I have a question for you. https://www.binance.com/uk-UA/register?ref=JHQQKNKN

  • Rastreador de teléfono celular – Aplicación de rastreo oculta que registra la ubicación, SMS, audio de llamadas, WhatsApp, Facebook, fotos, cámaras, actividad de Internet. Lo mejor para el control parental y la supervisión de empleados. Rastrear Teléfono Celular Gratis – Programa de Monitoreo en Línea.

  • La mejor aplicación de control parental para proteger a sus hijos – monitoriza en secreto GPS, SMS, llamadas, WhatsApp, Facebook, ubicación. Puede monitorear de forma remota las actividades del teléfono móvil después de descargar e instalar apk en el teléfono de destino.

  • Thanks for sharing. I read many of your blog posts, cool, your blog is very good. https://accounts.binance.com/zh-TC/register-person?ref=53551167

  • JseraldGat says:

    Cialis Presentaciones
    I consider, that you are not right. I am assured. I suggest it to discuss. Write to me in PM.
    Cialis 5 mg prezzo cialis prezzo cialis 5 mg prezzo

  • SLewistus says:

    Aviator Spribe казино играть на Mac
    I — the same opinion.
    Добро пожаловать в захватывающий мир авиаторов! Aviator – это увлекательная игра, которая позволит вам окунуться в атмосферу боевых действий на небе. Необычные графика и захватывающий сюжет сделают ваше путешествие по воздуху неповторимым.

    Попробуйте свою удачу в игре Aviator Spribe казино играть и получайте крупные призы!
    Aviator игра позволит вам почувствовать себя настоящим пилотом. Вам предстоит совершить невероятные маневры, выполнять сложные задания и сражаться с противниками. Улучшайте свой самолет, чтобы быть готовым к любым ситуациям и становиться настоящим мастером.
    Основные особенности Aviator краш игры:
    1. Реалистичная графика и физика – благодаря передовой графике и реалистичной физике вы почувствуете себя настоящим пилотом.
    2. Разнообразные режимы игры и миссии – в Aviator краш игре вы сможете выбрать различные режимы игры, такие как гонки, симулятор полетов и захватывающие воздушные бои. Кроме того, каждая миссия будет предлагать свои собственные вызовы и задачи.
    3. Улучшение и модернизация самолетов – в игре доступны различные модели самолетов, которые можно покупать и улучшать. Вы сможете устанавливать новое оборудование, улучшать двигательность и мощность своего самолета, а также выбирать различные варианты окраски и декорации.
    Aviator краш игра – это возможность испытать себя в роли авиатора и преодолеть все сложности и опасности воздушного пространства. Почувствуйте настоящую свободу и адреналин в Aviator краш игре онлайн!
    Играйте в «Авиатор» в онлайн-казино Pin-Up
    Aviator краш игра онлайн предлагает увлекательную и захватывающую игровую атмосферу, где вы становитесь настоящим авиатором и сражаетесь с самыми опасными искусственными интеллектами.
    В этой игре вы должны показать свое мастерство и смекалку, чтобы преодолеть сложности многочисленных локаций и уровней. Вам предстоит собирать бонусы, уклоняться от препятствий и сражаться с врагами, используя свои навыки пилотирования и стрельбы.
    Каждый уровень игры Aviator краш имеет свою уникальную атмосферу и задачи. Будьте готовы к неожиданностям, так как вас ждут захватывающие повороты сюжета и сложные испытания. Найдите все пути к победе и станьте настоящим героем авиатором!
    Авиатор игра является прекрасным способом провести время и испытать настоящий адреналиновый разряд. Готовы ли вы стать лучшим авиатором? Не упустите свой шанс и начните играть в Aviator краш прямо сейчас!
    Aviator – играй, сражайся, побеждай!
    Aviator Pin Up (Авиатор Пин Ап ) – игра на деньги онлайн Казахстан
    Aviator игра предлагает увлекательное и захватывающее разнообразие врагов и уровней, которые не оставят равнодушными даже самых требовательных геймеров.
    Враги в Aviator краш игре онлайн представлены в самых разных формах и размерах. Здесь вы встретите группы из маленьких и быстрых врагов, а также огромных боссов с мощным вооружением. Разнообразие врагов позволяет игрокам использовать разные тактики и стратегии для победы.
    Кроме того, Aviator игра предлагает разнообразие уровней сложности. Выберите легкий уровень, чтобы насладиться игровым процессом, или вызовите себе настоящий вызов, выбрав экспертный уровень. Независимо от выбранного уровня сложности, вы получите максимум удовольствия от игры и окунетесь в захватывающий мир авиаторов.
    Играйте в Aviator и наслаждайтесь разнообразием врагов и уровней, которые позволят вам почувствовать себя настоящим авиатором.

  • Thank you for your sharing. I am worried that I lack creative ideas. It is your article that makes me full of hope. Thank you. But, I have a question, can you help me? https://www.binance.info/id/join?ref=V3MG69RO

  • Dichaelfooff says:

    I savour, lead to I discovered exactly what I used to be looking for. You have ended my four day lengthy hunt! God Bless you man. Have a great day. Bye

    bitcoin price usd live

  • OLaneutese says:

    Мы предоставляем услуги Строительство дома из кирпича под ключ в Алматы, обеспечивая полный цикл работ от проектирования до завершения строительства. Наша команда опытных специалистов гарантирует высокое качество строительства и индивидуальный подход к каждому клиенту. Работаем с современными технологиями и материалами, чтобы создать дом вашей мечты в соответствии с вашими потребностями и ожиданиями.

  • This asset is unbelievable. The wonderful information exhibits the distributer’s earnestness. I’m stunned and anticipate more such astonishing sections.

Leave a Reply

Your email address will not be published. Required fields are marked *