December 8, 2022

SharewarePile.com – Latest Web Hosting News

Latest Web Development and Hosting News

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

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

See: Function and Class Components

Pure components

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

See: Pure components

Component API

These methods and properties are available for Component instances.

See: Component API

Lifecycle

Mounting

Method Description
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

Method Description
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

Hooks are a new addition in React 16.8.

See: Hooks at a Glance

Declaring multiple state variables

Effect hook

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

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

Use FriendStatus

See: Building Your Own Hooks

Hooks API Reference

Also see: Hooks FAQ

Basic Hooks

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

Full details: Basic Hooks

Additional Hooks

Hook Description
useReducer(reducer, initialArg, init)
useCallback(() => { … })
useMemo(() => { … })
useRef(initialValue)
useImperativeHandle(ref, () => { … })
useLayoutEffect identical 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

Allows access to DOM nodes.

See: Refs and the DOM

DOM Events

Pass functions to attributes like onChange.

See: Events

Other features

Transferring props

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

See Transferring props

Top-level API

There are more, but these are most common.

See: React top-level API

JSX patterns

Style shorthand

See: Inline styles

Inner HTML

See: Dangerously set innerHTML

Lists

Always supply a key property.

Conditionals

Short-circuit evaluation

New features

Returning multiple elements

You can return multiple elements as arrays or fragments.

Arrays

Fragments

See: Fragments and strings

Returning strings

You can return just a string.

See: Fragments and strings

Errors

Catch errors via componentDidCatch. (React 16+)

See: Error handling in React 16

Portals

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

See: Portals

Hydration

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

See: Hydrate

Property validation

PropTypes

See: Typechecking with PropTypes

Key Description
any Anything

Basic

Key Description
string
number
func Function
bool True or false

Enum

Key Description
oneOf(any) Enum types
oneOfType(type array) Union

Array

Key Description
array
arrayOf(…)

Object

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

Elements

Key Description
element React element
node DOM node

Required

Key Description
(···).isRequired Required

Basic types

Required types

Elements

Enumerables (oneOf)

Arrays and objects

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?


Go to Source of this post
Author Of this post: Rahul Sharma
Title Of post: React Js Cheat Sheet : Do You Really Need It? This Will Help You Decide!
Author Link: {authorlink}