React Lifecycle Cheat Sheet

Posted on  by 



  1. React Lifecycle Cheat Sheet Printable
  2. What Is The Order In React Lifecycle
  3. React Lifecycle Hook
  4. React Lifecycle Cheat Sheet Pdf
  5. Lifecycle Methods React
  6. React Component Lifecycle Events
  1. The Update life cycle and will not execute componentDidUpdate render Used to update the elements that are being rendered by the Component Other APIs setState(updater, callback) Enqueues changes to the component state and tells React that this component and its children need to be re-rendered with the updated state forceUpdate(callback).
  2. React lifecycle hooks. All of the react component lifecycle stages help us handle most of the moments precisely and perform actions that we need at that moment, but not always we need them. In many applications, we will need to catch only moments when we init component, update, and unmount, without going for all of the small parts.
  3. So In this cheat sheet, I will describe all the Flutter life-cycle methods, their React equivalent, and what they do. If you just want to check a simple lifecycle method, here is the list: Flutter life-cycle methods index.

A short guide to all the exported functions in React Testing Library

  • renderconst {/* */} = render(Component) returns:
    • unmount function to unmount the component
    • container reference to the DOM node where the component is mounted
    • all the queries from DOM Testing Library, bound to the document so thereis no need to pass a node as the first argument (usually, you can use thescreen import instead)
import{ render, fireEvent, screen }from'@testing-library/react'
test('loads items eventually',async()=>{

React supports three mounting lifecycle methods for component classes: componentWillMount , render , and componentDidMount. ComponentWillMount will be called first followed by the render method and finally the componentDidMount method. Each component has several “lifecycle methods” that you can override to run code at particular times in the process. You can use this lifecycle diagram as a cheat sheet. In the list below, commonly used lifecycle methods are marked as bold. The rest of them exist for relatively rare use cases.

fireEvent.click(getByText('Load'))
// Wait for page to update with query text
const items =await screen.findAllByText(/Item #[0-9]: /)
})

Queries#

Difference from DOM Testing Library

The queries returned from render in React Testing Library are the same asDOM Testing Library except they have the first argument bound to thedocument, so instead of getByText(node, 'text') you do getByText('text')

React Lifecycle Cheat Sheet

See Which query should I use?

No Match1 Match1+ MatchAwait?
getBythrowreturnthrowNo
findBythrowreturnthrowYes
queryBynullreturnthrowNo
getAllBythrowarrayarrayNo
findAllBythrowarrayarrayYes
queryAllBy[]arrayarrayNo
  • ByLabelText find by label or aria-label text content
    • getByLabelText
    • queryByLabelText
    • getAllByLabelText
    • queryAllByLabelText
    • findByLabelText
    • findAllByLabelText
  • ByPlaceholderText find by input placeholder value
    • getByPlaceholderText
    • queryByPlaceholderText
    • getAllByPlaceholderText
    • queryAllByPlaceholderText
    • findByPlaceholderText
    • findAllByPlaceholderText
  • ByText find by element text content
    • getByText
    • queryByText
    • getAllByText
    • queryAllByText
    • findByText
    • findAllByText
  • ByDisplayValue find by form element current value
    • getByDisplayValue
    • queryByDisplayValue
    • getAllByDisplayValue
    • queryAllByDisplayValue
    • findByDisplayValue
    • findAllByDisplayValue
  • ByAltText find by img alt attribute
    • getByAltText
    • queryByAltText
    • getAllByAltText
    • queryAllByAltText
    • findByAltText
    • findAllByAltText
  • ByTitle find by title attribute or svg title tag
    • getByTitle
    • queryByTitle
    • getAllByTitle
    • queryAllByTitle
    • findByTitle
    • findAllByTitle
  • ByRole find by aria role
    • getByRole
    • queryByRole
    • getAllByRole
    • queryAllByRole
    • findByRole
    • findAllByRole
  • ByTestId find by)
  • configure change global options:configure({testIdAttribute: 'my-data-test-id'})
  • cleanup clears the DOM (use with afterEach to resetDOM between tests)

Text Match Options#

Given the following HTML:

React Lifecycle Cheat Sheet Printable

Will find the div:

getByText('Hello World')// full string match
getByText('llo Worl',{ exact:false})// substring match
getByText('hello world',{ exact:false})// ignore case
// Matching a regex:
getByText(/world/i)// substring match, ignore case
getByText(/^hello world$/i)// full string match, ignore case
getByText((content, element)=> content.startsWith('Hello'))

Summary

What is React? React is a declarative JavaScript library for building user interfaces.We are able to build complex UIs from small, isolated pieces of code called ‘components’.These components tell us what we want to see on the screen. React handles the update andre-render of components.

Example

An example of a component is React.Component subclasses:

So what does this mean? ShoppingList is a React component class (akak React component type).A component takes in parameters (props, aka ‘properties’) and returns a hierarchy of views to displayvia the render method.

The render method returns a description of what you want to see on the screen. React takes this descriptionand displays the result, which is a React element (lightweight description of what to render).

React uses a special syntax called JSX which makes these structures easier to write. The <div /> syntaxis transformed at build time to React.createElement('div'). The example above turns into:

Top-level API

https://reactjs.org/docs/react-api.html

If you load React from a <script> tag, then these top-level APIs are available on the React global.

Tools

Google Chrome Extensions has a ‘React Developer Tools’ extensionWith this, in Chrome DevTools, you can click on the ‘Components’ section to look at React Components.

JSX

JSX is the syntax extension to JavaScript. We use JSX with React to describe what the UIshould look like. JSX produces React ‘elements’. It looks like this:

The idea is that React separates concerns with loosely coupled units called components.

You can put any type of JavaScript expressions inside the curly braces in JSX (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions)

Note: Recommend using the ‘Babel’ language definition for your editor for proper syntax highlightingFor VSCode, that means installing the extension ‘vscode-language-babel’

Elements

Elements are the smallest building blocks for React apps. An element describes what you see on the screen.React DOM handles updating the DOM to match the React elements. React’s components are made up of a lot of elements.

We normally have a single ‘root’ DOM node because everything inside it will be managed by React DOM.To render a React element into a root DOM node, pass both to ReactDOM.render(), like:

Updating a rendered element

React elements are immutable; once you create the elmenet, you cannot changes its children or attributes.The only way to update the UI is to create a new element and pass it to ReactDOM.render().

Even though we describe the whole UI tree each tick, React only updates the content that has changed (if any).

Components and Props

Components lets you split the UI into independent reusable pieces. Components can be defined as eitherclasses or functions (with classes providing more features). To define a React component, you need toextend React.Component. For reference, the component API is here: https://reactjs.org/docs/react-component.html

What Is The Order In React Lifecycle

Component (as class)

Here it is as a class

The only method you have to define in a React.Component sublcass is the render() method.The idea is that code reuse is primarily done through composition rather than inheritance.

Component (as function)

Here it is as a function (aka function components)

This is a valid React component because it accepts a single ‘props’ (properties) object argumentwith data and returns a React element.

Rendering a Component

Elements can be:

  • DOM tags
  • user-defined components

See examples below:

When React sees an element representing a user-defined component, it passes JSX attributes and childrento this component as a single object (aka ‘props’).

Example

Here we render a ‘Hello Will’ on the page:

Here’s what is happening:

  • React.Render() is called with the element <Welcome name='Will' />
  • React calls the Welcome component with the properties {name: 'Will'} as the props
  • The Welcome component returns a <h1>Hello Will</h1> element as the result
  • React DOM updates the DOM to match <h1>Hello Will</h1>

Note: Always start a component name with a capital letter. Starting with a lowercase lettermeans that this gets interpreted as a DOM tag instead of a component.

Components referring to components

Your components can refer to other components in their output. This gives us the same component abstractionfor any level of deatil. Everything (a button, a form, a screen) are all expressed as components.For this example, we have an App component that renders multiple Welcome components:

State

You can convert a function into a component class by calling it a class, adding a render() method,and replacing props with this.props like so:

To add state, we add a class constructor that assigns the inital this.state

Instead of updating based off a time (e.g. every 1 second update DOM), we use lifecyle methods(see ‘Lifecycle’):

So what’s going on?

1 The <Clock /> component is passed to ReactDOM.render() where React calls the constructor method.2 The constructor method initializes this.state with an object (the current time)3 React calls the Clock component’s render() method and React updates the DOM to match the render output4 When the Clock output is inserted into the DOM, React calls the componentDidMount() lifecycle method5 Inside this method, Clock asks the browser to set up a timer to call the component’s tick() method once a second6 Each second the browser calls the tick() method and the Clock component schedules a UI update by calling setState() with an object containing the current time. The setState() call lets React know that the state has changed so it calls render() method again to see what should be drawn (using the new this.state.date)7 If the Clock component is removed from the DOM, then React calls componentWillUnmount() method

Rules about State

Some rules about state:

Set state with setState()

  • do not modify state directly (e.g. this.state.comment = 'Something' is wrong)
  • instead, use setState() function (e.g. this.setState({comment: 'Hello'});)
  • the only place where you can assign this.state is in the constructor

State updates may be asynchronous

  • React batches multiple setState() calls into a single update for performance
  • That means this.props and this.state may be updated asynchronously so you should not rely on their valuesfor calculating the next state
  • Use the form of setState() that accepts a function rather than an object; that funtion will receive theprevious state as the first argument and the props at the time the update is applied as the second argument

For example:

State updates are merged

When you call setState(), React merges the object you provide into the current state.

Data Flows Down

Parent and child components do not know (and do not need to know) if a component is stateful or statelessThis is why state is called local or encapsulated. A component can pass its state down as propsto its child components like this:

The FormattedDate component can receive the date in its props and wouldn’t know whether it came fromthe Clock’s state, fromt he Clock’s props, or was typed by hand.

Lifecycle

Each component has several ‘lifecycle methods’ that you can override to run code at particular times in the process.The Lifecycle Cheat sheet is here: https://projects.wojtekmaj.pl/react-lifecycle-methods-diagram/The main lifecycle methods are for:

  • mounting
  • updating
  • unmounting

Mounting

These methods are called in this order when a component is created and inserted into the DOM:

  • constructor()
  • static getDerivedStateFromProps() (not used often)
  • render()
  • componentDidMount()

Updating

An update is caused by changes to props or state. These methods are called in the following order when a componentis being re-rendered:

  • static getDerivedStateFromProps() (not used often)
  • shouldComponentUpdate() (not used often)
  • render()
  • getSnapshotBeforeUpdate() (not used often)
  • componentDidUpdate()

Unmounting

This method is called when a component is being removed from the DOM:

React Lifecycle Hook

  • componentWillUnmount()

render() method

React Lifecycle Cheat Sheet Pdf

The render() method is the only required method in a class component.When called, it should examine this.props and this.state and return one of the following types:

  • React elements (usually through JSX), e.g. <div /> or <mycomponent />
  • Arrays and fragments (return multiple elements from render)
  • Portals - lets you render children into a different DOM subtree
  • Strings and numbers (i.e. text nodes in the DOM)
  • Booleans or null (i.e. renders nothing)

Renders should not modify component state and should return the same results each time it’s invoked

Handling Events

Handling events with React elements is similar to handling events on DOM elements.

  • React events use camelCase instead of lowercase
  • with JSX you pass a function as the event handler instead of a string

Say we have this HTML

Lifecycle Methods React

In React, this would be:

Prevent Default behavior

In React, to prevent default behavior, you cannot return false. Instead, you have tocall preventDefault explicitly. In HTML this might look like:

In React this would be:

Adding Listeners

With React, you do not need to call addEventListener to add listeners to a DOM element after it is created.Instead, provide a listener when the element is initially rendered. A common pattern is for an event handlerto be a method on the class. For example, the Toggle component renders a button that lets the user togglebetween ‘ON’ and ‘OFF’ states:

React Component Lifecycle Events

Passing additional arguments to event handlers

You can pass extra parameters to an event handler. Either of these would work to pass in an additional id param.

These two are the same, just one uses arrow functions and the other uses Function.prototype.bind.The e argument representing the React event will be passed as a second argument after the ID.With an arrow function, we explicitly pass e. With bind, any additional arguments are automatically forwarded.

Conditional Rendering

In React, you can create distinct components that encapsulate behavior you need. You can thenrender only some of them depending on the state of your application. Conditionals in React are the sameas conditions in Javascript, use an if or a conditional (ternary) operator to create elementsrepresenting the current state (and let React update the UI).





Coments are closed