SlideShare a Scribd company logo
In order for the code to compile, a JSX expression must have exactly one
outermost element. In the below block of code the <a> tag is the outermost
element.
const myClasses = (
<a href="https://www.codecademy.com">
<h1>
Sign Up!
</h1>
</a>
);
JSX is a syntax extension of JavaScript. It’s used to create DOM elements which
are then rendered in the React DOM.
A JavaScript file containing JSX will have to be compiled before it reaches a web
browser. The code block shows some example JavaScript code that will need to
be compiled.
import React from 'react';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<h1>Render me!</h1>);
/ Learn React
JSX
Nested JSX elements
JSX Syntax and JavaScript
Cheatsheets
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 1/9
A JSX expression that spans multiple lines must be wrapped in parentheses: (
and ) . In the example code, we see the opening parentheses on the same line
as the constant declaration, before the JSX expression begins. We see the
closing parentheses on the line following the end of the JSX expression.
const myList = (
<ul>
<li>item 1</li>
<li>item 2</li>
<li>item 3</li>
</ul>
);
In the block of code we see the similarities between JSX syntax and HTML: they
both use the angle bracket opening and closing tags ( <h1> and </h1> ).
When used in a React component, JSX will be rendered as HTML in the browser.
const title = <h1>Welcome all!</h1>
The syntax of JSX attributes closely resembles that of HTML attributes. In the
block of code, inside of the opening tag of the <h1> JSX element, we see an
id attribute with the value "example" .
const example = <h1 id="example">JSX Attributes</h1>;
Multiline JSX Expression
JSX syntax and HTML
JSX attributes
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 2/9
The JavaScript library react-dom/client contains the createRoot() method,
which is used to create a React root at the HTML element used as an argument.
The React root renders JSX elements to the DOM by taking a JSX expression,
creating a corresponding tree of DOM nodes, and adding that tree to the DOM.
The code example begins by creating a React root at the HTML element with the
id app and storing it in root . Then, using root ‘s render() method, the JSX
used as an argument is rendered.
import React from 'react';
import { createRoot } from 'react-dom/client';
const container = document.getElementById('app');
const root = createRoot(container);
root.render(<h1>This is an example.</h1>);
JavaScript expressions may be embedded within JSX expressions. The
embedded JavaScript expression must be wrapped in curly braces.
In the provided example, we are embedding the JavaScript expression 10 * 10
within the <h1> tag. When this JSX expression is rendered to the DOM, the
embedded JavaScript expression is evaluated and rendered as 100 as the
content of the <h1> tag.
let expr = <h1>{10 * 10}</h1>;
// above will be rendered as <h1>100</h1>
React uses Virtual DOM, which can be thought of as a blueprint of the DOM.
When any changes are made to React elements, the Virtual DOM is updated. The
Virtual DOM finds the differences between it and the DOM and re-renders only
the elements in the DOM that changed. This makes the Virtual DOM faster and
more efficient than updating the entire DOM.
ReactDOM JavaScript library
Embedding JavaScript in JSX
The Virtual Dom
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 3/9
In JSX, you can’t use the word class ! You have to use className instead. This
is because JSX gets translated into JavaScript, and class is a reserved word in
JavaScript.
When JSX is rendered, JSX className attributes are automatically rendered
as class attributes.
// When rendered, this JSX expression...
const heading = <h1 className="large-
heading">Codecademy</h1>;
// ...will be rendered as this HTML
<h1 class="large-heading">Codecademy</h1>
In JSX, && is commonly used to render an element based on a boolean
condition. && works best in conditionals that will sometimes do an action, but
other times do nothing at all.
If the expression on the left of the && evaluates as true, then the JSX on the
right of the && will be rendered. If the first expression is false, however, then
the JSX to the right of the && will be ignored and not rendered.
// All of the list items will display if
// baby is false and age is above 25
const tasty = (
<ul>
<li>Applesauce</li>
{ !baby && <li>Pizza</li> }
{ age > 15 && <li>Brussels Sprouts</li> }
{ age > 20 && <li>Oysters</li> }
{ age > 25 && <li>Grappa</li> }
</ul>
);
JSX className
JSX and conditional
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 4/9
JSX does not support if/else syntax in embedded JavaScript. There are three
ways to express conditionals for use with JSX elements:
1. a ternary within curly braces in JSX
2. an if statement outside a JSX element, or
3. the && operator.
// Using ternary operator
const headline = (
<h1>
{ age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff'
}
</h1>
);
// Using if/else outside of JSX
let text;
if (age >= drinkingAge) { text = 'Buy Drink' }
else { text = 'Do Teen Stuff' }
const headline = <h1>{ text }</h1>
// Using && operator. Renders as empty div if length is 0
const unreadMessages = [ 'hello?', 'remember me!'];
const update = (
<div>
{unreadMessages.length > 0 &&
<h1>
You have {unreadMessages.length} unread messages.
</h1>
}
</div>
JSX conditionals
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 5/9
);
Any text between JSX tags will be read as text content, not as JavaScript. In
order for the text to be read as JavaScript, the code must be embedded
between curly braces { } .
<p>{ Math.random() }</p>
// Above JSX will be rendered something like this:
<p>0.88</p>
In JSX, event listeners are specified as attributes on elements. An event listener
attribute’s name should be written in camelCase, such as onClick for an
onclick event, and onMouseOver for an onmouseover event.
An event listener attribute’s value should be a function. Event listener functions
can be declared inline or as variables and they can optionally take one argument
representing the event.
// Basic example
const handleClick = () => alert("Hello world!");
const button = <button onClick={handleClick}>Click
here</button>;
// Example with event parameter
const handleMouseOver = (event) =>
event.target.style.color = 'purple';
const button2 = <div onMouseOver={handleMouseOver}>Drag
here to change color</div>;
Embedding JavaScript code in JSX
JSX element event listeners
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 6/9
When writing JSX, it’s common to set attributes using embedded JavaScript
variables.
const introClass = "introduction";
const introParagraph = <p className={introClass}>Hello
world</p>;
The array method map() comes up often in React. It’s good to get in the habit
of using it alongside JSX.
If you want to create a list of JSX elements from a given array, then map() over
each element in the array, returning a list item for each one.
const strings = ['Home', 'Shop', 'About Me'];
const listItems = strings.map(string => <li>{string}
</li>);
<ul>{listItems}</ul>
In JSX, empty elements must explicitly be closed using a closing slash at the end
of their tag: <tagName /> .
A couple examples of empty element tags that must explicitly be closed include
<br> and <img> .
<br />
<img src="example_url" />
Setting JSX attribute values with embedded JavaScript
JSX .map() method
JSX empty elements syntax
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 7/9
The React.createElement() function is used by React to actually create virtual
DOM elements from JSX. When the JSX is compiled, it is replaced by calls to
React.createElement() .
You usually won’t write this function yourself, but it’s useful to know about.
// The following JSX...
const h1 = <h1 className="header">Hello world</h1>;
// ...will be compiled to the following:
const h1 = React.createElement(
'h1',
{
className: 'header',
},
'Hello world'
);
In JSX elements in a list, the key attribute is used to uniquely identify individual
elements. It is declared like any other attribute.
Keys can help performance because they allow React to keep track of whether
individual list items should be rendered, or if the order of individual items is
important.
<ul>
<li key="key1">One</li>
<li key="key2">Two</li>
<li key="key3">Three</li>
<li key="key4">Four</li>
</ul>
React.createElement() Creates Virtual DOM Elements
JSX key attribute
6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 8/9
React function components must contain a return statement. This should
return some React elements created with JSX.
function MyComponent() {
return <h1>Hello from MyComponent!</h1>;
}
React function components follow regular JavaScript class syntax in declaration
and returns JSX elements.
This example shows a simple React function component.
function MyComponent() {
return <h1>Hello world!</h1>;
}
In order to use React, we must first import the React library. When we import
the library, it creates an object that contains properties needed to make React
work, including JSX and creating custom components.
import React from 'react';
/ Learn React
React Components
return statement
Function Component Base
Importing React
Cheatsheets
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 1/7
A React component is a reusable piece of code used to define the appearance,
behavior, and state of a portion of a web app’s interface. Components are
defined as functions. Using the component as a factory, an infinite number of
component instances can be created.
import React from 'react';
function MyFunctionComponent() {
return <h1>Hello from a function component!</h1>;
}
class MyClassComponent extends React.Component {
render() {
return <h1>Hello from a class component!</h1>;
}
}
React requires that the first letter of components be capitalized. JSX will use this
capitalization to tell the difference between an HTML tag and a component
instance. If the first letter of a name is capitalized, then JSX knows it’s a
component instance; if not, then it’s an HTML element.
// This is considered a component by React.
<ThisComponent />
// This is considered a JSX HTML tag.
<div>
React Components
JSX Capitalization
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 2/7
React components can be modularly structured and made reusable by placing
them into their own files. Components can be exported and imported into a
top-level file and rendered.
In Greeting.js:
function Greeting() {
return (
<>
<h1>Hello, welcome to...</h1>
<h2>Learn React!</h2>
</>
);
}
export default Greeting;
In App.js:
import Greeting from './Greeting'
Importing and Exporting Components in React
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 3/7
A React function component can be rendered by creating a root container and
rendering the component into the root container.
//Component to be rendered
function MyComponent() {
return <h1>Hello, World!</h1>
}
//Rendering the component
ReactDOM.createRoot(
document.getElementById('app')
).render(<MyComponent />);
Rendering a Component
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 4/7
Parentheses are used when writing a multi-line JSX expression. In the example,
we see that the component’s return statement is split over multiple lines.
Therefore it is wrapped in parentheses.
return (
<blockquote>
<p>Be the change you wish to see in the world.</p>
<cite>
<a
target="_blank"
href="https://en.wikipedia.org/wiki/Mahatma_Gandhi"
>
Mahatma Gandhi
</a>
</cite>
</blockquote>
);
A React component can contain JavaScript before any JSX is returned. The
JavaScript before the return statement informs any logic necessary to render
the component.
In the example code, we see JavaScript prior to the return statement which
rounds the value to an integer.
function Integer() {
const value = 3.14;
const asInteger = Math.round(value);
return <p>{asInteger}</p>;
}
Multi-line JSX Expressions
Logic Before return
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 5/7
In React, JSX attribute values can be set through data stored in regular
JavaScript objects. We see this in the example block of code.
In our code example we first see our JavaScript object seaAnemones and the
values stored with this image. We then see how these stored values are used to
set the <img> attributes in our JSX expression for the SeaAnemones
component.
const seaAnemones = {
src:
'https://commons.wikimedia.org/wiki/Category:Images#/medi
a/File:Anemones_0429.jpg',
alt: 'Sea Anemones',
width: '300px',
};
function SeaAnemones () {
return (
<div>
<h1>Colorful Sea Anemones</h1>
<img
src={seaAnemones.src}
alt={seaAnemones.alt}
width={seaAnemones.width}
/>
</div>
);
}
Object Properties As Attribute Values
6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 6/7
A function component can return any JSX, including a mix of HTML elements and
custom React components.
In the example, we return a <Logo /> component and a “vanilla” HTML title.
This assumes that <Logo /> is defined elsewhere.
function Header() {
return (
<div>
<Logo />
<h1>Codecademy</h1>
</div>
);
}
React components can access their props with the props object.
In the example code below, we see the <Hello> component being rendered
with a firstName prop. It is accessed in the component’s return statement with
props.firstName .
This should render the text “Hi there, Kim!”
function Hello(props) {
return <h1>Hi there, {props.firstName}!</h1>;
}
ReactDOM.createRoot(document.getElementById('app')).rende
r(<Hello firstName="Kim" />)
/ Learn React
Components Interacting
Returning HTML Elements and Components
Accessing Props
Cheatsheets
6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 1/3
A React component can contain default values to be used in case props are
not passed. If any prop is not passed to a Component, its value will be replaced
by the prop of the same name.
In the example code, defaultProps is set so that profiles have a fallback profile
picture if none is set. The <MyFriends> component should return two
profiles: one with a set profile picture and one with the fallback profile picture.
function Profile(props) {
return (
<div>
<img src={props.profilePictureSrc} alt="" />
<h2>{props.name}</h2>
</div>
);
}
Profile.defaultProps = {
profilePictureSrc: 'https://example.com/no-profile-
picture.jpg',
};
function MyFriends(props) {
return (
<div>
<h1>My friends</h1>
<Profile
name="Jane Doe"
profilePictureSrc="https://example.com/jane-
doe.jpg"
/>
<Profile name="John Smith" />
</div>
);
defaultProps
6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 2/3
}
Components can pass information to other components. When one component
passes information to another, it is passed as props through one or more
attributes.
The example code demonstrates the use of attributes in props. SpaceShip is
the component and ride is the attribute. The SpaceShip component will
receive ride in its props.
<SpaceShip ride="Millennium Falcon" />
Every component’s props object has a property named children . Using
props.children will return everything in between a component’s opening and
closing JSX tags.
<List> // opening tag
<li></li> // child 1
<li></li> // child 2
<li></li> // child 3
</List> // closing tag
props
props.children
Print Share
6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 3/3
Hooks are functions that let us “hook into” state and lifecycle functionality in
function components.
Hooks allow us to:
reuse stateful logic between components
simplify and organize our code to separate concerns, rather allowing
unrelated data to get tangled up together
avoid confusion around the behavior of the this keyword
avoid class constructors, binding methods, and related advanced
JavaScript techniques
/ Learn React
Hooks
Why Hooks?
Cheatsheets
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 1/7
There are two main rules to keep in mind when using hooks:
1. Only call hooks from React function components.
2. Only call hooks at the top level, to be sure that hooks are called in the
same order each time a component renders.
Common mistakes to avoid are calling hooks inside of loops, conditions, or
nested functions.
// Instead of confusing React with code like this:
if (userName !== '') {
useEffect(() => {
localStorage.setItem('savedUserName', userName);
});
}
// We can accomplish the same goal, while consistently
calling our hook every time:
useEffect(() => {
if (userName !== '') {
localStorage.setItem('savedUserName', userName);
}
});
The primary purpose of a React component is to return some JSX to be
rendered. Often, it is helpful for a component to execute some code that
performs side effects in addition to rendering JSX.
In class components, side effects are managed with lifecycle methods. In
function components, we manage side effects with the Effect Hook. Some
common side effects include: fetching data from a server, subscribing to a data
stream, logging values to the console, interval timers, and directly interacting
with the DOM.
Rules for Using Hooks
Side Effects
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 2/7
The useEffect hook performs side effects every time a component renders.
useEffect accepts two arguments in the form of useEffect(callback,
dependencies) . The callback argument holds the side-effect logic and is
executed every time a render happens.
import React, { useState, useEffect } from 'react';
function TitleCount() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `You clicked ${count} times`;
}, [count]);
return <button onClick={(prev) => setCount(prev + 1)}>+
</button>;
}
The cleanup function is optionally returned by the first argument of the Effect
Hook.
If the effect does anything that needs to be cleaned up to prevent memory
leaks, then the effect returns a cleanup function. The Effect Hook will call this
cleanup function before calling the effect again as well as when the component
is being removed from the DOM.
useEffect(() => {
document.addEventListener('keydown', handleKeydown);
//Clean up the effect:
return () => document.removeEventListener('keydown',
handleKeydown);
});
The Effect Hook
Effect Cleanup Functions
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 3/7
useEffect() may be called more than once in a component. This gives us the
freedom to individually configure our dependency arrays, separate concerns,
and organize the code.
function App(props) {
const [title, setTitle] = useState('');
useEffect(() => {
document.title = title;
}, [title]);
const [time, setTime] = useState(0);
useEffect(() => {
const intervalId = setInterval(() => setTime((prev) =>
prev + 1), 1000);
return () => clearInterval(intervalId);
}, []);
// ...
}
Multiple Effect Hooks
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 4/7
The dependency array is used to tell the useEffect() method when to call the
effect.
By default, with no dependency array provided, the effect is called after
every render.
An empty dependency array signals that the effect never needs to be re-
run.
A non-empty dependency array signals that the hook runs the effect only
when any of the dependency array values changes.
useEffect(() => {
alert('called after every render');
});
useEffect(() => {
alert('called after first render');
}, []);
useEffect(() => {
alert('called when value of `endpoint` or `id`
changes');
}, [endpoint, id]);
The useState() Hook lets you add React state to function components. It
should be called at the top level of a React function definition to manage its
state.
initialState is an optional value that can be used to set the value of
currentState for the first render. The stateSetter function is used to update
the value of currentState and rerender our component with the next state
value.
const [currentState, stateSetter] =
useState(initialState);
Effect Dependency Array
The State Hook
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 5/7
When the previous state value is used to calculate the next state value, pass a
function to the state setter. This function accepts the previous value as an
argument and returns an updated value.
If the previous state is not used to compute the next state, just pass the next
state value as the argument for the state setter.
function Counter({ initialCount }) {
const [count, setCount] = useState(initialCount);
return (
<div>
Count: {count}
<button onClick={() =>
setCount(initialCount)}>Reset</button>
<button onClick={() => setCount((prevCount) =>
prevCount - 1)}>-</button>
<button onClick={() => setCount((prevCount) =>
prevCount + 1)}>+</button>
</div>
);
}
useState() may be called more than once in a component. This gives us the
freedom to separate concerns, simplify our state setter logic, and organize our
code in whatever way makes the most sense to us!
function App() {
const [sport, setSport] = useState('basketball');
const [points, setPoints] = useState(31);
const [hobbies, setHobbies] = useState([]);
}
State Setter Callback Function
Multiple State Hooks
6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 6/7
In React, a stateful component is a component that holds some state. Stateless
components, by contrast, have no state. Note that both types of components
can use props.
In the example, there are two React components. The Store component is
stateful and the Week component is stateless.
function Store() {
const [sell, setSell] = useState("anything");
return <h1>I'm selling {sell}.</h1>;
}
function Week(props){
return <h1>Today is {props.day}!</h1>;
}
/ Learn React
React Programming Patterns
Stateful and Stateless Components
Cheatsheets
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 1/7
One of the most common programming patterns in React is to use stateful
parent components to maintain their own state and pass it down to one or more
stateless child components as props. The example code shows a basic example.
// This is a stateless child component.
function BabyYoda(props) {
return <h2>I am {props.name}!</h2>;
}
// This is a stateful Parent element.
function Yoda() {
const [ name, setName ] = useState("Toyoda")
// The child component will render information passed
down from the parent component.
return <BabyYoda name={name} />;
}
React Programming Pattern
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 2/7
In React, a component should never change its own props directly. A parent
component should change them.
State, on the other hand, is the opposite of props: a component keeps track of
its own state and can change it at any time.
The example code shows a component that accepts a prop, subtitle , which
never changes. It also has a state object which does change.
function Clock(props) {
const [ date, setDate ] = useState(new Date());
const updateTime = () => {
setDate(new Date());
}
return (
<div>
<h1>It is currently {date.toLocaleTimeString()}
</h1>
<h2>{props.subtitle}</h2>
<button onClick={updateTime}>Update the
clock</button>
</div>
);
}
Changing Props and State
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 3/7
If a React parent component defines a function that changes its state, that
function can be passed to a child component and called within the component
to updating the parent component’s state.
In this example, because this.setState() causes the Name component to re-
render, any change to the <input> will update the Name component’s state,
causing a new render and displaying the new state value to the <p> tag
content.
function Name() {
const [name, setName] = useState('');
const handleNameChange = (e) => {
setName(e.target.value);
}
return (
<div>
<input onChange={handleNameChange} />
<p>{name}</p>
</div>
);
}
Passing State Change Functions as Props
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 4/7
Event handler functions in React are often used to update state. These handler
functions often receive an event as an argument, which is used to update state
values correctly.
In the example code, we use event.target.value to get the input’s value.
function MyComponent() {
const [ text, setText ] = useState("");
const handleChange(event) => {
setText(event.target.value);
}
return (
<div>
<input onChange={handleChange} value={text} />
<p>You typed {text}</p>
</div>
);
}
Event Handlers and State in React
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 5/7
A common programming pattern in React is to have presentational and
container components. Container components contain business logic (methods)
and handle state. Presentational components render that behavior and state to
the user.
In the example code, CounterContainer is a container component and
Counter is a presentational component.
class CounterContainer extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
this.increment = this.increment.bind(this);
}
increment() {
this.setState((oldState) => {
return { count: oldState.count + 1 };
});
}
render() {
return <Counter count={this.state.count} increment=
{this.increment} />;
}
}
class Counter extends React.Component {
render() {
return (
<div>
<p>The count is {this.props.count}.</p>
<button onClick={this.props.increment}>Add
1</button>
</div>
Presentational and Container Components
6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 6/7
React supports inline CSS styles for elements. Styles are supplied as a style
prop with a JavaScript object.
// Passing the styles as an object
const color = {
color: 'blue',
background: 'sky'
};
<h1 style={color}>Hello</h1>
// Passing the styles with an inline object, as a
shorthand
<h1 style={{ color: 'red' }}>I am red!</h1>
/ Learn React
React Styles
React CSS Styles
Cheatsheets
6/3/24, 5:08 PM Learn React: React Styles Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-styles/cheatsheet 1/2
In React, style names are written in “camelCase”, unlike in CSS where they are
hyphenated. In most cases, style values are written as strings. When entering
numeric values, you don’t have to enter px because React automatically
interprets them as pixel values.
// Styles in CSS:
// font-size: 20px;
// color: blue;
// Would look like this style object in React:
const style = {
fontSize: 20,
color: 'blue',
};
Style Names And Values
Print Share
6/3/24, 5:08 PM Learn React: React Styles Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-styles/cheatsheet 2/2
In React, form fields are considered either uncontrolled, meaning they maintain
their own state, or controlled, meaning that some parent maintains their state
and passes it to them to display. Usually, the form fields will be controlled.
The example code shows an uncontrolled and controlled input.
const uncontrolledInput = <input />;
const controlledInput = (
<input value={stateValue} onChange={handleInputChange}
/>
);
A controlled form element in React is built with a change handler function and a
value attribute.
const controlledInput = (
<input value={stateValue} onChange={handleInputChange}
/>
);
/ Learn React
React Forms
Controlled vs. Uncontrolled Form Fields
Controlled Components
Cheatsheets
Print Share
6/3/24, 5:09 PM Learn React: React Forms Cheatsheet | Codecademy
https://www.codecademy.com/learn/react-101/modules/react-forms/cheatsheet 1/1

More Related Content

PDF
Why I Love JSX!
PPTX
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
PDF
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
PDF
Stay with React.js in 2020
PDF
Learn react by Etietop Demas
PPTX
Introduction to JSX
PDF
Understanding React JSX_ A Beginner's Guide
PDF
ReactJS for Programmers
Why I Love JSX!
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
unit 3_Adv WTAdvanced Web Tecg Design_HTML_CSS_JAVASCRIPT_AJAX_PPT.pdf
Stay with React.js in 2020
Learn react by Etietop Demas
Introduction to JSX
Understanding React JSX_ A Beginner's Guide
ReactJS for Programmers

Similar to React cheetsheet. This is cheetsheet note of react (20)

PDF
30 days-of-react-ebook-fullstackio
PDF
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
PPTX
Learn react.js with me!
PPT
PPTX
React JSX.pptx
PPTX
React & Redux for noobs
PPTX
ReactJS.pptx
PPTX
slides.pptx
PPTX
slides.pptx
PPTX
Unit 2 Fundamentals of React -------.pptx
PPTX
Introduction to React and MobX
PDF
Frontin like-a-backer
PPTX
Intro react js
PPTX
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
PDF
Full Stack React Workshop [CSSC x GDSC]
PDF
Building web applications with React (Jfokus)
PDF
Introduction to React for Frontend Developers
PDF
Welcome to React & Flux !
PDF
React enlightenment
30 days-of-react-ebook-fullstackio
ReactJS Tutorial For Beginners | ReactJS Redux Training For Beginners | React...
Learn react.js with me!
React JSX.pptx
React & Redux for noobs
ReactJS.pptx
slides.pptx
slides.pptx
Unit 2 Fundamentals of React -------.pptx
Introduction to React and MobX
Frontin like-a-backer
Intro react js
React JS; all concepts. Contains React Features, JSX, functional & Class comp...
Full Stack React Workshop [CSSC x GDSC]
Building web applications with React (Jfokus)
Introduction to React for Frontend Developers
Welcome to React & Flux !
React enlightenment
Ad

More from RajKumar64326 (6)

PPT
structure of the Geographical Information System
PDF
Git_Commands_Cheat_Sheet. command for github
PDF
Multimedia lesson1-intro it contain the basic information of multimedia
PDF
AI crash course for beginners it is a best course for AI beginner
PDF
Unit8 GIS it is the course of the geographic information system
PPTX
YatraFit-Your-Fitness-Journey-Companion (1).pptx
structure of the Geographical Information System
Git_Commands_Cheat_Sheet. command for github
Multimedia lesson1-intro it contain the basic information of multimedia
AI crash course for beginners it is a best course for AI beginner
Unit8 GIS it is the course of the geographic information system
YatraFit-Your-Fitness-Journey-Companion (1).pptx
Ad

Recently uploaded (20)

PDF
HVAC Specification 2024 according to central public works department
PPTX
B.Sc. DS Unit 2 Software Engineering.pptx
PDF
LDMMIA Reiki Yoga Finals Review Spring Summer
PPTX
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
PPTX
A powerpoint presentation on the Revised K-10 Science Shaping Paper
PPTX
Computer Architecture Input Output Memory.pptx
PDF
Empowerment Technology for Senior High School Guide
PDF
My India Quiz Book_20210205121199924.pdf
PDF
Environmental Education MCQ BD2EE - Share Source.pdf
PDF
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Uderstanding digital marketing and marketing stratergie for engaging the digi...
DOC
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
PDF
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
PDF
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
PDF
Chinmaya Tiranga quiz Grand Finale.pdf
PDF
Weekly quiz Compilation Jan -July 25.pdf
PPTX
Unit 4 Computer Architecture Multicore Processor.pptx
PDF
IGGE1 Understanding the Self1234567891011
PPTX
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx
HVAC Specification 2024 according to central public works department
B.Sc. DS Unit 2 Software Engineering.pptx
LDMMIA Reiki Yoga Finals Review Spring Summer
Chinmaya Tiranga Azadi Quiz (Class 7-8 )
A powerpoint presentation on the Revised K-10 Science Shaping Paper
Computer Architecture Input Output Memory.pptx
Empowerment Technology for Senior High School Guide
My India Quiz Book_20210205121199924.pdf
Environmental Education MCQ BD2EE - Share Source.pdf
MBA _Common_ 2nd year Syllabus _2021-22_.pdf
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Uderstanding digital marketing and marketing stratergie for engaging the digi...
Soft-furnishing-By-Architect-A.F.M.Mohiuddin-Akhand.doc
FOISHS ANNUAL IMPLEMENTATION PLAN 2025.pdf
A GUIDE TO GENETICS FOR UNDERGRADUATE MEDICAL STUDENTS
Chinmaya Tiranga quiz Grand Finale.pdf
Weekly quiz Compilation Jan -July 25.pdf
Unit 4 Computer Architecture Multicore Processor.pptx
IGGE1 Understanding the Self1234567891011
ELIAS-SEZIURE AND EPilepsy semmioan session.pptx

React cheetsheet. This is cheetsheet note of react

  • 1. In order for the code to compile, a JSX expression must have exactly one outermost element. In the below block of code the <a> tag is the outermost element. const myClasses = ( <a href="https://www.codecademy.com"> <h1> Sign Up! </h1> </a> ); JSX is a syntax extension of JavaScript. It’s used to create DOM elements which are then rendered in the React DOM. A JavaScript file containing JSX will have to be compiled before it reaches a web browser. The code block shows some example JavaScript code that will need to be compiled. import React from 'react'; import { createRoot } from 'react-dom/client'; const container = document.getElementById('app'); const root = createRoot(container); root.render(<h1>Render me!</h1>); / Learn React JSX Nested JSX elements JSX Syntax and JavaScript Cheatsheets 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 1/9
  • 2. A JSX expression that spans multiple lines must be wrapped in parentheses: ( and ) . In the example code, we see the opening parentheses on the same line as the constant declaration, before the JSX expression begins. We see the closing parentheses on the line following the end of the JSX expression. const myList = ( <ul> <li>item 1</li> <li>item 2</li> <li>item 3</li> </ul> ); In the block of code we see the similarities between JSX syntax and HTML: they both use the angle bracket opening and closing tags ( <h1> and </h1> ). When used in a React component, JSX will be rendered as HTML in the browser. const title = <h1>Welcome all!</h1> The syntax of JSX attributes closely resembles that of HTML attributes. In the block of code, inside of the opening tag of the <h1> JSX element, we see an id attribute with the value "example" . const example = <h1 id="example">JSX Attributes</h1>; Multiline JSX Expression JSX syntax and HTML JSX attributes 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 2/9
  • 3. The JavaScript library react-dom/client contains the createRoot() method, which is used to create a React root at the HTML element used as an argument. The React root renders JSX elements to the DOM by taking a JSX expression, creating a corresponding tree of DOM nodes, and adding that tree to the DOM. The code example begins by creating a React root at the HTML element with the id app and storing it in root . Then, using root ‘s render() method, the JSX used as an argument is rendered. import React from 'react'; import { createRoot } from 'react-dom/client'; const container = document.getElementById('app'); const root = createRoot(container); root.render(<h1>This is an example.</h1>); JavaScript expressions may be embedded within JSX expressions. The embedded JavaScript expression must be wrapped in curly braces. In the provided example, we are embedding the JavaScript expression 10 * 10 within the <h1> tag. When this JSX expression is rendered to the DOM, the embedded JavaScript expression is evaluated and rendered as 100 as the content of the <h1> tag. let expr = <h1>{10 * 10}</h1>; // above will be rendered as <h1>100</h1> React uses Virtual DOM, which can be thought of as a blueprint of the DOM. When any changes are made to React elements, the Virtual DOM is updated. The Virtual DOM finds the differences between it and the DOM and re-renders only the elements in the DOM that changed. This makes the Virtual DOM faster and more efficient than updating the entire DOM. ReactDOM JavaScript library Embedding JavaScript in JSX The Virtual Dom 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 3/9
  • 4. In JSX, you can’t use the word class ! You have to use className instead. This is because JSX gets translated into JavaScript, and class is a reserved word in JavaScript. When JSX is rendered, JSX className attributes are automatically rendered as class attributes. // When rendered, this JSX expression... const heading = <h1 className="large- heading">Codecademy</h1>; // ...will be rendered as this HTML <h1 class="large-heading">Codecademy</h1> In JSX, && is commonly used to render an element based on a boolean condition. && works best in conditionals that will sometimes do an action, but other times do nothing at all. If the expression on the left of the && evaluates as true, then the JSX on the right of the && will be rendered. If the first expression is false, however, then the JSX to the right of the && will be ignored and not rendered. // All of the list items will display if // baby is false and age is above 25 const tasty = ( <ul> <li>Applesauce</li> { !baby && <li>Pizza</li> } { age > 15 && <li>Brussels Sprouts</li> } { age > 20 && <li>Oysters</li> } { age > 25 && <li>Grappa</li> } </ul> ); JSX className JSX and conditional 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 4/9
  • 5. JSX does not support if/else syntax in embedded JavaScript. There are three ways to express conditionals for use with JSX elements: 1. a ternary within curly braces in JSX 2. an if statement outside a JSX element, or 3. the && operator. // Using ternary operator const headline = ( <h1> { age >= drinkingAge ? 'Buy Drink' : 'Do Teen Stuff' } </h1> ); // Using if/else outside of JSX let text; if (age >= drinkingAge) { text = 'Buy Drink' } else { text = 'Do Teen Stuff' } const headline = <h1>{ text }</h1> // Using && operator. Renders as empty div if length is 0 const unreadMessages = [ 'hello?', 'remember me!']; const update = ( <div> {unreadMessages.length > 0 && <h1> You have {unreadMessages.length} unread messages. </h1> } </div> JSX conditionals 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 5/9
  • 6. ); Any text between JSX tags will be read as text content, not as JavaScript. In order for the text to be read as JavaScript, the code must be embedded between curly braces { } . <p>{ Math.random() }</p> // Above JSX will be rendered something like this: <p>0.88</p> In JSX, event listeners are specified as attributes on elements. An event listener attribute’s name should be written in camelCase, such as onClick for an onclick event, and onMouseOver for an onmouseover event. An event listener attribute’s value should be a function. Event listener functions can be declared inline or as variables and they can optionally take one argument representing the event. // Basic example const handleClick = () => alert("Hello world!"); const button = <button onClick={handleClick}>Click here</button>; // Example with event parameter const handleMouseOver = (event) => event.target.style.color = 'purple'; const button2 = <div onMouseOver={handleMouseOver}>Drag here to change color</div>; Embedding JavaScript code in JSX JSX element event listeners 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 6/9
  • 7. When writing JSX, it’s common to set attributes using embedded JavaScript variables. const introClass = "introduction"; const introParagraph = <p className={introClass}>Hello world</p>; The array method map() comes up often in React. It’s good to get in the habit of using it alongside JSX. If you want to create a list of JSX elements from a given array, then map() over each element in the array, returning a list item for each one. const strings = ['Home', 'Shop', 'About Me']; const listItems = strings.map(string => <li>{string} </li>); <ul>{listItems}</ul> In JSX, empty elements must explicitly be closed using a closing slash at the end of their tag: <tagName /> . A couple examples of empty element tags that must explicitly be closed include <br> and <img> . <br /> <img src="example_url" /> Setting JSX attribute values with embedded JavaScript JSX .map() method JSX empty elements syntax 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 7/9
  • 8. The React.createElement() function is used by React to actually create virtual DOM elements from JSX. When the JSX is compiled, it is replaced by calls to React.createElement() . You usually won’t write this function yourself, but it’s useful to know about. // The following JSX... const h1 = <h1 className="header">Hello world</h1>; // ...will be compiled to the following: const h1 = React.createElement( 'h1', { className: 'header', }, 'Hello world' ); In JSX elements in a list, the key attribute is used to uniquely identify individual elements. It is declared like any other attribute. Keys can help performance because they allow React to keep track of whether individual list items should be rendered, or if the order of individual items is important. <ul> <li key="key1">One</li> <li key="key2">Two</li> <li key="key3">Three</li> <li key="key4">Four</li> </ul> React.createElement() Creates Virtual DOM Elements JSX key attribute 6/3/24, 4:59 PM Learn React: JSX Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-101-jsx-u/cheatsheet 8/9
  • 9. React function components must contain a return statement. This should return some React elements created with JSX. function MyComponent() { return <h1>Hello from MyComponent!</h1>; } React function components follow regular JavaScript class syntax in declaration and returns JSX elements. This example shows a simple React function component. function MyComponent() { return <h1>Hello world!</h1>; } In order to use React, we must first import the React library. When we import the library, it creates an object that contains properties needed to make React work, including JSX and creating custom components. import React from 'react'; / Learn React React Components return statement Function Component Base Importing React Cheatsheets 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 1/7
  • 10. A React component is a reusable piece of code used to define the appearance, behavior, and state of a portion of a web app’s interface. Components are defined as functions. Using the component as a factory, an infinite number of component instances can be created. import React from 'react'; function MyFunctionComponent() { return <h1>Hello from a function component!</h1>; } class MyClassComponent extends React.Component { render() { return <h1>Hello from a class component!</h1>; } } React requires that the first letter of components be capitalized. JSX will use this capitalization to tell the difference between an HTML tag and a component instance. If the first letter of a name is capitalized, then JSX knows it’s a component instance; if not, then it’s an HTML element. // This is considered a component by React. <ThisComponent /> // This is considered a JSX HTML tag. <div> React Components JSX Capitalization 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 2/7
  • 11. React components can be modularly structured and made reusable by placing them into their own files. Components can be exported and imported into a top-level file and rendered. In Greeting.js: function Greeting() { return ( <> <h1>Hello, welcome to...</h1> <h2>Learn React!</h2> </> ); } export default Greeting; In App.js: import Greeting from './Greeting' Importing and Exporting Components in React 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 3/7
  • 12. A React function component can be rendered by creating a root container and rendering the component into the root container. //Component to be rendered function MyComponent() { return <h1>Hello, World!</h1> } //Rendering the component ReactDOM.createRoot( document.getElementById('app') ).render(<MyComponent />); Rendering a Component 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 4/7
  • 13. Parentheses are used when writing a multi-line JSX expression. In the example, we see that the component’s return statement is split over multiple lines. Therefore it is wrapped in parentheses. return ( <blockquote> <p>Be the change you wish to see in the world.</p> <cite> <a target="_blank" href="https://en.wikipedia.org/wiki/Mahatma_Gandhi" > Mahatma Gandhi </a> </cite> </blockquote> ); A React component can contain JavaScript before any JSX is returned. The JavaScript before the return statement informs any logic necessary to render the component. In the example code, we see JavaScript prior to the return statement which rounds the value to an integer. function Integer() { const value = 3.14; const asInteger = Math.round(value); return <p>{asInteger}</p>; } Multi-line JSX Expressions Logic Before return 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 5/7
  • 14. In React, JSX attribute values can be set through data stored in regular JavaScript objects. We see this in the example block of code. In our code example we first see our JavaScript object seaAnemones and the values stored with this image. We then see how these stored values are used to set the <img> attributes in our JSX expression for the SeaAnemones component. const seaAnemones = { src: 'https://commons.wikimedia.org/wiki/Category:Images#/medi a/File:Anemones_0429.jpg', alt: 'Sea Anemones', width: '300px', }; function SeaAnemones () { return ( <div> <h1>Colorful Sea Anemones</h1> <img src={seaAnemones.src} alt={seaAnemones.alt} width={seaAnemones.width} /> </div> ); } Object Properties As Attribute Values 6/3/24, 5:06 PM Learn React: React Components Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components/cheatsheet 6/7
  • 15. A function component can return any JSX, including a mix of HTML elements and custom React components. In the example, we return a <Logo /> component and a “vanilla” HTML title. This assumes that <Logo /> is defined elsewhere. function Header() { return ( <div> <Logo /> <h1>Codecademy</h1> </div> ); } React components can access their props with the props object. In the example code below, we see the <Hello> component being rendered with a firstName prop. It is accessed in the component’s return statement with props.firstName . This should render the text “Hi there, Kim!” function Hello(props) { return <h1>Hi there, {props.firstName}!</h1>; } ReactDOM.createRoot(document.getElementById('app')).rende r(<Hello firstName="Kim" />) / Learn React Components Interacting Returning HTML Elements and Components Accessing Props Cheatsheets 6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 1/3
  • 16. A React component can contain default values to be used in case props are not passed. If any prop is not passed to a Component, its value will be replaced by the prop of the same name. In the example code, defaultProps is set so that profiles have a fallback profile picture if none is set. The <MyFriends> component should return two profiles: one with a set profile picture and one with the fallback profile picture. function Profile(props) { return ( <div> <img src={props.profilePictureSrc} alt="" /> <h2>{props.name}</h2> </div> ); } Profile.defaultProps = { profilePictureSrc: 'https://example.com/no-profile- picture.jpg', }; function MyFriends(props) { return ( <div> <h1>My friends</h1> <Profile name="Jane Doe" profilePictureSrc="https://example.com/jane- doe.jpg" /> <Profile name="John Smith" /> </div> ); defaultProps 6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 2/3
  • 17. } Components can pass information to other components. When one component passes information to another, it is passed as props through one or more attributes. The example code demonstrates the use of attributes in props. SpaceShip is the component and ride is the attribute. The SpaceShip component will receive ride in its props. <SpaceShip ride="Millennium Falcon" /> Every component’s props object has a property named children . Using props.children will return everything in between a component’s opening and closing JSX tags. <List> // opening tag <li></li> // child 1 <li></li> // child 2 <li></li> // child 3 </List> // closing tag props props.children Print Share 6/3/24, 5:06 PM Learn React: Components Interacting Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/learn-react-components-interacting/cheatsheet 3/3
  • 18. Hooks are functions that let us “hook into” state and lifecycle functionality in function components. Hooks allow us to: reuse stateful logic between components simplify and organize our code to separate concerns, rather allowing unrelated data to get tangled up together avoid confusion around the behavior of the this keyword avoid class constructors, binding methods, and related advanced JavaScript techniques / Learn React Hooks Why Hooks? Cheatsheets 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 1/7
  • 19. There are two main rules to keep in mind when using hooks: 1. Only call hooks from React function components. 2. Only call hooks at the top level, to be sure that hooks are called in the same order each time a component renders. Common mistakes to avoid are calling hooks inside of loops, conditions, or nested functions. // Instead of confusing React with code like this: if (userName !== '') { useEffect(() => { localStorage.setItem('savedUserName', userName); }); } // We can accomplish the same goal, while consistently calling our hook every time: useEffect(() => { if (userName !== '') { localStorage.setItem('savedUserName', userName); } }); The primary purpose of a React component is to return some JSX to be rendered. Often, it is helpful for a component to execute some code that performs side effects in addition to rendering JSX. In class components, side effects are managed with lifecycle methods. In function components, we manage side effects with the Effect Hook. Some common side effects include: fetching data from a server, subscribing to a data stream, logging values to the console, interval timers, and directly interacting with the DOM. Rules for Using Hooks Side Effects 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 2/7
  • 20. The useEffect hook performs side effects every time a component renders. useEffect accepts two arguments in the form of useEffect(callback, dependencies) . The callback argument holds the side-effect logic and is executed every time a render happens. import React, { useState, useEffect } from 'react'; function TitleCount() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }, [count]); return <button onClick={(prev) => setCount(prev + 1)}>+ </button>; } The cleanup function is optionally returned by the first argument of the Effect Hook. If the effect does anything that needs to be cleaned up to prevent memory leaks, then the effect returns a cleanup function. The Effect Hook will call this cleanup function before calling the effect again as well as when the component is being removed from the DOM. useEffect(() => { document.addEventListener('keydown', handleKeydown); //Clean up the effect: return () => document.removeEventListener('keydown', handleKeydown); }); The Effect Hook Effect Cleanup Functions 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 3/7
  • 21. useEffect() may be called more than once in a component. This gives us the freedom to individually configure our dependency arrays, separate concerns, and organize the code. function App(props) { const [title, setTitle] = useState(''); useEffect(() => { document.title = title; }, [title]); const [time, setTime] = useState(0); useEffect(() => { const intervalId = setInterval(() => setTime((prev) => prev + 1), 1000); return () => clearInterval(intervalId); }, []); // ... } Multiple Effect Hooks 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 4/7
  • 22. The dependency array is used to tell the useEffect() method when to call the effect. By default, with no dependency array provided, the effect is called after every render. An empty dependency array signals that the effect never needs to be re- run. A non-empty dependency array signals that the hook runs the effect only when any of the dependency array values changes. useEffect(() => { alert('called after every render'); }); useEffect(() => { alert('called after first render'); }, []); useEffect(() => { alert('called when value of `endpoint` or `id` changes'); }, [endpoint, id]); The useState() Hook lets you add React state to function components. It should be called at the top level of a React function definition to manage its state. initialState is an optional value that can be used to set the value of currentState for the first render. The stateSetter function is used to update the value of currentState and rerender our component with the next state value. const [currentState, stateSetter] = useState(initialState); Effect Dependency Array The State Hook 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 5/7
  • 23. When the previous state value is used to calculate the next state value, pass a function to the state setter. This function accepts the previous value as an argument and returns an updated value. If the previous state is not used to compute the next state, just pass the next state value as the argument for the state setter. function Counter({ initialCount }) { const [count, setCount] = useState(initialCount); return ( <div> Count: {count} <button onClick={() => setCount(initialCount)}>Reset</button> <button onClick={() => setCount((prevCount) => prevCount - 1)}>-</button> <button onClick={() => setCount((prevCount) => prevCount + 1)}>+</button> </div> ); } useState() may be called more than once in a component. This gives us the freedom to separate concerns, simplify our state setter logic, and organize our code in whatever way makes the most sense to us! function App() { const [sport, setSport] = useState('basketball'); const [points, setPoints] = useState(31); const [hobbies, setHobbies] = useState([]); } State Setter Callback Function Multiple State Hooks 6/3/24, 5:07 PM Learn React: Hooks Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-hooks-u/cheatsheet 6/7
  • 24. In React, a stateful component is a component that holds some state. Stateless components, by contrast, have no state. Note that both types of components can use props. In the example, there are two React components. The Store component is stateful and the Week component is stateless. function Store() { const [sell, setSell] = useState("anything"); return <h1>I'm selling {sell}.</h1>; } function Week(props){ return <h1>Today is {props.day}!</h1>; } / Learn React React Programming Patterns Stateful and Stateless Components Cheatsheets 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 1/7
  • 25. One of the most common programming patterns in React is to use stateful parent components to maintain their own state and pass it down to one or more stateless child components as props. The example code shows a basic example. // This is a stateless child component. function BabyYoda(props) { return <h2>I am {props.name}!</h2>; } // This is a stateful Parent element. function Yoda() { const [ name, setName ] = useState("Toyoda") // The child component will render information passed down from the parent component. return <BabyYoda name={name} />; } React Programming Pattern 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 2/7
  • 26. In React, a component should never change its own props directly. A parent component should change them. State, on the other hand, is the opposite of props: a component keeps track of its own state and can change it at any time. The example code shows a component that accepts a prop, subtitle , which never changes. It also has a state object which does change. function Clock(props) { const [ date, setDate ] = useState(new Date()); const updateTime = () => { setDate(new Date()); } return ( <div> <h1>It is currently {date.toLocaleTimeString()} </h1> <h2>{props.subtitle}</h2> <button onClick={updateTime}>Update the clock</button> </div> ); } Changing Props and State 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 3/7
  • 27. If a React parent component defines a function that changes its state, that function can be passed to a child component and called within the component to updating the parent component’s state. In this example, because this.setState() causes the Name component to re- render, any change to the <input> will update the Name component’s state, causing a new render and displaying the new state value to the <p> tag content. function Name() { const [name, setName] = useState(''); const handleNameChange = (e) => { setName(e.target.value); } return ( <div> <input onChange={handleNameChange} /> <p>{name}</p> </div> ); } Passing State Change Functions as Props 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 4/7
  • 28. Event handler functions in React are often used to update state. These handler functions often receive an event as an argument, which is used to update state values correctly. In the example code, we use event.target.value to get the input’s value. function MyComponent() { const [ text, setText ] = useState(""); const handleChange(event) => { setText(event.target.value); } return ( <div> <input onChange={handleChange} value={text} /> <p>You typed {text}</p> </div> ); } Event Handlers and State in React 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 5/7
  • 29. A common programming pattern in React is to have presentational and container components. Container components contain business logic (methods) and handle state. Presentational components render that behavior and state to the user. In the example code, CounterContainer is a container component and Counter is a presentational component. class CounterContainer extends React.Component { constructor(props) { super(props); this.state = { count: 0 }; this.increment = this.increment.bind(this); } increment() { this.setState((oldState) => { return { count: oldState.count + 1 }; }); } render() { return <Counter count={this.state.count} increment= {this.increment} />; } } class Counter extends React.Component { render() { return ( <div> <p>The count is {this.props.count}.</p> <button onClick={this.props.increment}>Add 1</button> </div> Presentational and Container Components 6/3/24, 5:08 PM Learn React: React Programming Patterns Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-programming-patterns/cheatsheet 6/7
  • 30. React supports inline CSS styles for elements. Styles are supplied as a style prop with a JavaScript object. // Passing the styles as an object const color = { color: 'blue', background: 'sky' }; <h1 style={color}>Hello</h1> // Passing the styles with an inline object, as a shorthand <h1 style={{ color: 'red' }}>I am red!</h1> / Learn React React Styles React CSS Styles Cheatsheets 6/3/24, 5:08 PM Learn React: React Styles Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-styles/cheatsheet 1/2
  • 31. In React, style names are written in “camelCase”, unlike in CSS where they are hyphenated. In most cases, style values are written as strings. When entering numeric values, you don’t have to enter px because React automatically interprets them as pixel values. // Styles in CSS: // font-size: 20px; // color: blue; // Would look like this style object in React: const style = { fontSize: 20, color: 'blue', }; Style Names And Values Print Share 6/3/24, 5:08 PM Learn React: React Styles Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-styles/cheatsheet 2/2
  • 32. In React, form fields are considered either uncontrolled, meaning they maintain their own state, or controlled, meaning that some parent maintains their state and passes it to them to display. Usually, the form fields will be controlled. The example code shows an uncontrolled and controlled input. const uncontrolledInput = <input />; const controlledInput = ( <input value={stateValue} onChange={handleInputChange} /> ); A controlled form element in React is built with a change handler function and a value attribute. const controlledInput = ( <input value={stateValue} onChange={handleInputChange} /> ); / Learn React React Forms Controlled vs. Uncontrolled Form Fields Controlled Components Cheatsheets Print Share 6/3/24, 5:09 PM Learn React: React Forms Cheatsheet | Codecademy https://www.codecademy.com/learn/react-101/modules/react-forms/cheatsheet 1/1