React v16+ Cheat Sheet (PDF/JPG/Custom themes)

React v16+ Cheat Sheet (PDF/JPG/Custom themes)

Save yourself some time with this React cheat sheet

Sometimes, it can take 30 minutes to create a quick interface using React. But other times, it can take hours.

If you often forget the names of methods, properties, or the functionality they provide, it can become irritating to have to leave your code editor just for a Google search. You may be thinking, is it really that hard to type in a couple of letters and get the answers you want? Well, absolutely not. But if this happens more than once, then maybe it’s time to acquire a cheat sheet so that you don’t have to leave your code editor anymore. Having a cheat sheet next to you will certainly save you some time in the long run!

Here’s a cheat sheet you can use:

While you’re looking at the cheat sheet, just keep in mind that you can:

1. Generate the cheat sheet into a downloadable PDF/JPEG, or you can bookmark the page and come back to it at a later time.

2. If you don't like how the columns are ordered, you can drag and re-order them before you generate the cheat sheet.

3. You can select any of the code syntax themes in the select box to generate in the cheat sheet (there are about 25 themes you can choose from):

I’ll go ahead and put this in a public repo if anyone needs it. I also just began this yesterday, and so it may not be a perfect cheat sheet yet.

Also, my goal was to fit all of this into one page, but there was too much information. If anyone has any suggestions on which parts to swap/remove, feel free to let me know.

The changes will also stay after you close your browser so that you don’t have to redo everything. Here’s a full list of what’s in the cheat sheet so far (I will keep updating the cheat sheet over time).

Fragments

// Does not support key attribute
const App = () => (
  <>
    <MyComponent />
  </>
)
// Supports key attribute
const App = () => (
  <React.Fragment key="abc123">
    <MyComponent />
  </React.Fragment>
)

Return Types

const App = () => 'a basic string' // string
const App = () => 1234567890 // number
const App = () => true // boolean
const App = () => null // null
const App = () => <div /> // react element
const App = () => <MyComponent /> // component
const App = () => [
  // array
  'a basic string',
  1234567890,
  true,
  null,
  <div />,
  <MyComponent />,
]

Error Boundary (React v16.0)

class MyErrorBoundary extends React.Component {
  state = { hasError: false }
  componentDidCatch(error, info) {...}
  render() {
    if (this.state.hasError) return <SomeErrorUI />
    return this.props.children
  }
}

const App = () => ( <MyErrorBoundary> <Main /> </MyErrorBoundary> )

Static Methods

// Returning object = New props require state update
// Returning null = New props do not require state update
class MyComponent extends React.Component {
  static getDerivedStateFromProps(props, state) {...}
  state = {...}
}

// Return value is passed as 3rd argument to componentDidUpdate class MyComponent extends React.Component { static getSnapshotBeforeUpdate(prevProps, prevState) {...} }

// Listening to context from a class component import SomeContext from '../SomeContext' class MyCompmonent extends React.Component { static contextType = SomeContext componentDidMount() { console.log(this.context) } }

// Enables rendering fallback UI before render completes class MyComponent extends React.Component { state getDerivedStateFromError() {...} state = { error: null } componentDidCatch(error, info) {...} }

Component States

// Class component state
class MyComponent extends React.Component {
  state = { loaded: false }
  componentDidMount = () => this.setState({ loaded: true })
  render() {
    if (!this.state.loaded) return null
    return <div {...this.props} />
  }
}

// Function component state (useState/useReducer) const MyComponent = (props) => { // With useState const [loaded, setLoaded] = React.useState(false) // With useReducer const [state, dispatch] = React.useReducer(reducer, initialState) if (!loaded) return null React.useEffect(() => void setLoaded(true)) return <div {...props} />

Rendering Components

// Ways to render Card
const Card = (props) => <div {...props} />

const App = ({ items = [] }) => { const renderCard = (props) => <Card {...props} /> return items.map(renderCard) // or return items.map((props) => renderCard(props)) }

const App = (props) => <Card {...props} />

class App extends React.Component { render() { return <Card {...this.props} /> } }

const MyComp = ({ component: Component }) => <Component /> const App = () => <MyComp component={Card} />

Default Props

// Function component
const MyComponent = (props) => <div {...props} />
MyComponent.defaultProps = { fruit: 'apple' }

// Class component class MyComponent extends React.Component { static defaultProps = { fruit: 'apple' }

render() { return <div {...this.props} /> } }

Other React Exports

// createContext (React v16.3)
const WeatherContext = React.createContext({ day: 3 })

const App = ({ children }) => { const [weather, setWeather] = React.useState(null) const [error, setError] = React.useState(null)

React.useEffect(() => { api.getWeather(...) .then(setWeather) .catch(setError) }, [])

const contextValue = { weather, error }

return ( <WeatherContext.Provider value={contextValue}> {children} </WeatherContext.Provider> ) } const SomeChild = () => { const { weather } = React.useContext(WeatherContext) console.log(weather) return null }

// createRef (Obtain a reference to a react node) (React v16.3) const App = () => { const ref = React.createRef() React.useEffect(() => { console.log(ref.current) }, []) return <div ref={ref} /> }

// forwardRef (Pass the ref down to a child) (React v16.3) const Remote = React.forwardRef((props, ref) => ( <div ref={ref} {...props} /> ))

const App = () => { const ref = React.createRef() return <Remote ref={ref} /> }

// memo (Optimize your components to avoid wasteful renders) (React v16.6) const App = () => {...} const propsAreEqual = (props, nextProps) => { return props.id === nextProps.id } // Does not re-render if id is the same export default React.memo(App, propsAreEqual)

Importing

// default export
const App = (props) => <div {...props} />
export default App
import App from './App'

// named export export const App = (props) => <div {...props} /> import { App } from './App'

Pointer Events (React v16.4)

onPointerUp           onPointerDown
onPointerMove         onPointerCancel
onGotPointerCapture   onLostPointerCapture
onPointerEnter        onPointerLeave
onPointerOver         onPointerOut

const App = () => { const onPointerDown = (e) => console.log(e.pointerId) return <div onPointerDown={onPointerDown} /> }

React Suspense/Lazy (React v16.6)

// lazy -> Dynamic import. Reduces bundle size
// + Code splitting
const MyComponent = React.lazy(() => import('./MyComponent))
const App = () => <MyComponent />

// Suspend rendering while components are waiting for something // + Code splitting import LoadingSpinner from '../LoadingSpinner'

const App = () => ( <React.Suspense fallback={<LoadingSpinner />}> <MyComponent /> </React.Suspense> )

React Profiler (React v16.9)

const App = () => (
  <React.StrictMode>
    <div>
      <MyComponent />
      <OtherComponent />
    </div>
  </React.StrictMode>
)

Synchronous / Asynchronous act Test Utility (React v16.9)

import { act } from 'react-dom/test-utils'
import MyComponent from './MyComponent'

const container = document.createElement('div')

// Synchronous it('renders and adds new item to array', () => { act(() => { ReactDOM.render(<MyComponent />, container) }) const btn = container.querySelector('button') expect(btn.textContent).toBe('one item') act(() => { button.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) expect(btn.textContent).toBe('two items') })

// Asynchronous it('does stuff', async () => { await act(async () => { // code }) })

Check out the cheat sheet here.

Conclusion

And that’s the end of this post! I hope you found this to be useful and lookout for more in the future!

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow us on Facebook | Twitter

Further reading about React, Redux and Django

React - The Complete Guide (incl Hooks, React Router, Redux)

Modern React with Redux [2019 Update]

Best 50 React Interview Questions for Frontend Developers in 2019

JavaScript Basics Before You Learn React

Microfrontends — Connecting JavaScript frameworks together (React, Angular, Vue etc)

Reactjs vs. Angularjs — Which Is Best For Web Development

React + TypeScript : Why and How

How To Write Better Code in React

React Router: Add the Power of Navigation

Getting started with React Router

Using React Router for optimizing React apps

Creating RESTful APIs with NodeJS and MongoDB Tutorial

reactjs javascript web-development

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Hire Web Developer

Looking for an attractive & user-friendly web developer? HourlyDeveloper.io, a leading web, and mobile app development company, offers web developers for hire through flexible engagement models. You can **[Hire Web...

ReactJS Web App Development Services

We provide top-notch ReactJS development services to global clients. Hire expert ReactJS developers from top React JS development company, Skenix Infotech.

Why Web Development is Important for your Business

With the rapid development in technology, the old ways to do business have changed completely. A lot more advanced and developed ways are ...

Important Reasons to Hire a Professional Web Development Company

    You name the business and I will tell you how web development can help you promote your business. If it is a startup or you seeking some...

Hire Dedicated eCommerce Web Developers | Top eCommerce Web Designers

Build your eCommerce project by hiring our expert eCommerce Website developers. Our Dedicated Web Designers develop powerful & robust website in a short span of time.