Joshua's Cheatsheets - React / JSX - Cheatsheet

Other resources

What & Link Type
"The React Handbook" by Flavio Copes - Online version PDF signup
   ---> Amazing resource!
"React for Vue Developers" by Sebastian De Deyne Guide / Cheatsheet
React Lifecycles Method Diagram Cheatsheet
React+TypeScript Cheatsheets Cheatsheet
PluralSight: Composing React Components with TypeScript Guide
Post: "You Probably Don't Need Derived State" Guide
Collection: enaqx/awesome-react Collection

Binding template literal

Binding template literal to property expecting string: You have to use double brackets to "break out" of JSX and into regular JS. Instead of:

<SEO title="`${props.pageContext.slug}`" />

You need:

<SEO title={`${props.pageContext.slug}`} />

Creating unique keys

You want a unique identifier, which is actually harder than one might expect to create. Using the index provided within a loop is not recommended, and even combining with something like (new Date()).getTime() is not guaranteed to be unique.

There are tons of packages out there that you can drop in to create unique Ids. Or just make a composite key out of enough unique parameters to ensure non-duplicates.

Misc / How Do I...

  • You can now use empty elements, known as fragments, to wrap siblings:

    • <><div></div><div></div></>
  • Issues returning JSX?

    • More than one line? Make sure wrapped in parenthesis return (<div></div>)
    • Make sure there is *only one* root level element
  • Pass a bunch of options to a component as props (basically convert JS Obj to props)

    • Just use spread operator - {...this.props}
  • Simulate a change event on a <input> element

  • How to add an external stylesheet (not for bundling)

    • Instead of using import within a JS file (like App.js), add the stylesheet directly as a link tag element in the HTML file (e.g. <link rel="stylesheet" href="https://.../style.css" />)
  • How do I access an element directly (similar to native browser APIs like document.getElementById) in React? How do I get the DOM node?

    • That is a great use case for React refs! - Docs
    • Options:

      • Newest and recommended: useRef hook

        • myRef = useRef(null)
      • Older:- this.myRef = React.createRef() in class constructor
    • You can access DOM node through myRef.current, after attaching via <MyElement ref={myRef}/>
  • What's with the {} curly braces? Is this Mustache or Handlebars templating?

    • No, the curly braces simply tell the JSX compiler that you are about to give it something that should be evaluated as a JavaScript Expression, rather than a string or component.


  • You can assign JSX to variables! Makes it very easy to reuse!
  • Make use of object destructuring assignments to avoid repetitive props syntax

    • const {hidden, dataArr, isAdmin, isAuthed} = this.props
    • -> Or, destructure right in function argument, const myComponent = ({hidden, dataArr, isAdmin, isAuthed}) => {}
  • You can use class members and/or regular vars to hold changing values, as opposed to putting in state/props, if you want to avoid unnecessary renders when those values are not part of UI

Asset management and usage

You have two main options when it comes to asset management:

  • Public Folder: Place in /public

    • Pull into HTML with %PUBLIC_URL%
    • Pull into JS with process.env.PUBLIC_URL
  • Bundling: Place asset files alongside JS, in /src

    • Pull into JS by using import at top of file with relatively path
    • Pull into css (e.g. for background image) with relative path

The second option is always preferred, since it uses webpack to bundle assets and will help keep the size of your app down by only bundling assets that are actually used (as well as some other tricks).

Importing assets in JS or CSS



import background from './assets/background.jpg';
// ...
render() {
	return (
		<img src={background} />


#main {
	background-image: url(./assets/background.jpg);

Getting around method binding of this

A common issue with React is preserving the value of this, especially when it comes to event handlers, like onClick.

If the callback you are assigning uses this within its body, you will have issues if the value of this changes (most often in a Cannot read property '___' of undefined error).

Here are some ways to ensure the value of this stays the way you want it to:

Explicit, with .bind() on the attribute

The older method was commonly to use .bind() to explicitly bind the value of this at the point of attaching the handler. That might look something like this:

<CustomComponent onClick={this.handleEvent.bind(this)}>

ES6 Class binding

If you are using the new ES6 class syntax, you have all the other options, plus a few more. Let's say this is our base code:

class MyComponent extends React.Component {
	constructor(props) {
		this.state = {counter: 0};

	handleClick(evt) {
		const updatedCount = this.state.counter + 1;
			counter: updatedCount

	render() {
		return (
			<button onClick={this.handleClick}> Counter + </button>

One option is to use .bind(), in the constructor:

constructor(props) {
	this.state = {counter: 0};
	// ADDED:
	this.handleClick = this.handleClick.bind(this);

Another option is to turn the handleClick method, into a member, that is the value of an arrow function, thus automatically binding this to the class:

// Rest of class definition
// Or: public handleClick = (evt) => {}
handleClick = (evt) => {
	const updatedCount = this.state.counter + 1;
		counter: updatedCount
// ...

Technically, this is actually an ES6 public field, which is, as of 2019, in an experimental stage, so while it is well supported with transpiled JS/TS, it has limited native browser support.

Inline arrow functions

One of the benefits (or drawbacks) of arrow functions is that they lexically bind this - automatically. So, if you do:

<CustomComponent onClick={(evt) => {

It doesn't matter if CustomComponent has a different this scope, because the arrow function binds the callback where you defined it!

Use createReactClass

If you use createReactClass, you generally don't have to worry about this issue, as createReactClass uses autobinding, which basically does .bind() for you.

More reading

Computed properties

Unlike Vue, which has a specific syntax for computed properties, React doesn't really care how you try to formulate values based on computed state properties.

ES6 Class - Getter

With the new ES6 class based approach, a very clean solution is to use getters, with something like:

class MyComponent extends React.Component {
	// ... class stuff
	get isAdult() {
		return typeof(this.state.age) === 'number' && this.state.age > 18;

Within the render function itself

There is nothing preventing you from computing a value within the render function itself. For example:

class MyComponent extends React.Component {
	// ... class stuff
	render() {
		const isAdult = typeof(this.state.age) === 'number' && this.state.age > 18;
		return (
				Is adult = {isAdult.toString()}

As a function

Another vanilla solution here is to simply use a function to return the computed value, rather than anything else. How you declare this is up to you:

  • Explicitly, with function myFunction(){}
  • As a ES6 class member

    • public isAdult() {}
  • With an arrow function to bind this

    • const isAdult = () => {};
  • Etc.

To use within your render method, simply make sure you actually execute it by following it with the parenthesis and arguments if applicable.

State management system

If you are using a dedicated state management system, there is a chance that what you are using might already have something in place to not only provide explicit computed properties, but also optimize them, to prevent redundant expensive re-calculations.

For example, if you use MobX, make sure to check out this page on computed values.

Further reading:

Handlebars / Mustache type logic (loops, conditional, etc)

Conditional rendering

Tons of options - see "7 ways to implement conditional rendering".

Some tricky ones to remember, but can be very helpful are:

  • AND (&&) operator to show or hide

    • You can use {shouldShowBool && <div>I'll only show up if shouldShowBool is true!</div>}
    • This works because in JS, A && B returns B if A is true, without coercing B to a boolean
  • Ternary Operator (_?_:_) to swap between things

    • You can use {isLeaving ? <p>Goodbye!</p> : <p>Hello!</p>}

Loop / array render

The main way to render an array of something in React is to simply pass an array of JSX, within a JavaScript Expression block (e.g. {myJsxArr}). However, there are many ways to write this code:

You could:

  • Create an array of JSX template code assigned to a variable, and use it within render(), with something like: items.push(<div key={UNIQUE_KEY}>{CONTENT}</div>);
  • Iterate over the items directly in render(), and return the template there:

    const render = function() {
    	const items = ['bread', 'milk', 'cookies'];
    	return (
    			{, index) => {
    				return <li key={index}>{value}</li>
  • Use an IIFE to construct and return the array, all inline within the JSX:

    	<h1>One through Ten:</h1>
    	{(function () {
    		const jsxArr = [];
    		for (let x = 1; x <= 10; x++) {
    			jsxArr.push(<p key={x}>Number {x}</p>);
    		return jsxArr;
    • This is kind of an anti-pattern, so I would avoid and instead construct the array further up in the component before starting to return JSX / HTML.

React Hooks

What are React Hooks?

React hooks partially came about because of, and an alternative to, the complexity and boilerplate involved with class based components (as opposed to functions) and/or HOCs (higher order components). They are not required to be used, but many new devs prefer them for readability and isolation.

At their core, the key value proposition of React hooks is that they allow you to hook more directly into the React lifecycle and core APIs, such as state, props, etc.

Built-In React Hooks

Hook What
useState Get and set state
useEffect Wrap a function that contains possibly effectful code, which will be called after render.

You can conditionally trigger it by passing a dependency array as the second argument.

You can use it as a cleanup method (before component unmounts), by returning a cleanup function.
useContext Returns the current value for a given context object (object from React.createContext). Value is from nearest Provider.

A context value change will always trigger a re-render.

Using this with a context provider is a common alternative to prop-drilling, and/or large global state management systems.
useReducer An alternative to useState that basically takes a function to mutate state, rather than the state update directly.
useCallback Meant for optimization, you pass a callback and the dependencies that the callback uses to produce a result, and you get back a memoized (i.e. cached) callback function that only changes if the dependencies change.
useMemo Close to useCallback, but returns a memoized value, rather than a callback, that is only recomputed if the dependencies change.
useRef Returns a special mutable reference object, which can be updated, but persists across re-renders and does not trigger re-renders on change.

Value can be accessed with .current.
useImperativeHandle Lets you modify the reference that is passed to parent components (for example, to add a method onto ref.current). If used, should be combined with forwardRef, but also not recommended, period.
useLayoutEffect Essentially the same as useEffect, but fires after all DOM updates have occurred (e.g. at componentDidMount, or componentDidUpdate)
useDebugValue For custom hooks, you can use this to display a special label for the hook inside the React DevTools.

Building Your Own Hooks

You can easily write, share, and reuse custom hooks across many different components. In fact, this is one of the main selling points of hooks:

Hooks allow you to reuse stateful logic without changing your component hierarchy.

To create and re-use a hook, simply define it as an exported function, and then import where you need to use it. See the docs for details.

Custom React Hook - Sample Syntax

Remember to prefix with use.

Here is a general template:

export function useMyHook() {
	// Instantiate state vars
	const [myHookState, setMyHookState] = useState(null);

	// Setup code to update the hook state and handle removal
	useEffect(() => {
		// Register things (e.g. listeners, subscriptions, etc) to call setMyHookState
		return () => {
			// Un-register things that will call setMyHookState

	// Don't forget to return the state / val
	return myHookState;

Custom React Hooks - Examples

React Hook - Window Dimensions
export const useWindowSize = () => {
	const [size, setSize] = useState([0, 0]);
	useLayoutEffect(() => {
		// Need to hold function reference so we can use it for cleanup
		const updateSize = () => {
			setSize([window.innerWidth, window.innerHeight]);
		window.addEventListener('resize', updateSize);
		return () => window.removeEventListener('resize', updateSize);
	}, []);
	return size;

Chaining Hooks

You can "chain" hooks, where one hook update triggers another, by pulling them in as dependencies (second argument to useEffect).

For example, if I've already created a useWindowSize hook that updates when the window is resized, I could reuse that hook as the trigger to re-calculate the size of an element on the page, like so:

export const useElemSize = (elementRef) => {
	const [size, setSize] = useState({ width: 0, height: 0 });

	// Use windowSize hook as trigger to re-evaluate
	const windowSize = useWindowSize();

	useEffect(() => {
		try {
			const elem = elementRef.current;
			/** @type {DOMRect} */
			const domRect = elem.getBoundingClientRect();
				width: domRect.width,
				height: domRect.height
		} catch (e) {
			setSize({ width: 0, height: 0 });
	}, [windowSize, elementRef]);

	return size;
Markdown Source Last Updated:
Sat Apr 11 2020 03:22:56 GMT+0000 (Coordinated Universal Time)
Markdown Source Created:
Wed Aug 21 2019 20:31:01 GMT+0000 (Coordinated Universal Time)
© 2020 Joshua Tzucker, Built with Gatsby