This React CheatSheet provides an overview of the React library, detailing its use for building user interfaces with reusable components and efficient state management. It covers key concepts such as managing state with useState and useReducer, handling side effects with useEffect, and utilizing the Context API for state sharing. Additionally, it introduces hooks for performance optimization and reusability, including useMemo, useCallback, and custom hooks.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0 ratings0% found this document useful (0 votes)
6 views
react-cheatsheet
This React CheatSheet provides an overview of the React library, detailing its use for building user interfaces with reusable components and efficient state management. It covers key concepts such as managing state with useState and useReducer, handling side effects with useEffect, and utilizing the Context API for state sharing. Additionally, it introduces hooks for performance optimization and reusability, including useMemo, useCallback, and custom hooks.
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 14
React
CheatSheet
fy} CODE HELPIn this Cheatsheet, we will cover the basics of React. We will
provide examples to help you understand how React works and
how to use them in your own web development projects. Whether
you are a beginner or an experienced developer, this PDF can
serve as a useful reference guide.
(Op REACT
React is a JavaScript library for building user interfaces. It was
developed and is maintained by Facebook and a community of
individual developers and companies. React allows developers to
build reusable UI components, manage the state of their
applications, and render dynamic updates efficiently.
React uses a virtual DOM (Document Object Model) to update
the view without having to reload the entire page. This results in
fast and smooth updates to the user interface. React also uses a
component-based architecture, which allows developers to easily
reuse and compose their components to build complex UIs.
React is used for both web and mobile development, and is
popular for its simplicity, versatility, and performance. Many
companies and organizations use React for their websites and
applications, including Facebook, Airbnb, Netflix, and Dropbox.MANAGE STATE
useState
const [count, setCount] = useState(initialCount);
« Class way
const initialCount = 0;
class Counter extends Component {
constructor(props) {
super(props);
this.state = { count : initialCount };
}
render(Q) {
return (
You clicked {this.state.count} times
%
+
}« Hook Way
import { useState } from "react";
const initialCount = 0;
function Counter() {
const [count, setCount] = useState(initialCount);
return (
You clicked {count} times
3
}
useReducer
const [state, dispatch] = useReducer(
reducer,
initialState,
initialDispatch
%
An alternative to useState. Use it in the components that need
complex state management, such as multiple state values being
updated by multiple methods.const initialState = {count: 0};
function reducer(state, action) {
switch (action.type) {
case ‘increment’:
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
throw new ErrorQ;
}
}
function Counter({initialState}) {
const [state, dispatch] = useReducer(reducer, initialState);
return (
oy
Count: {state.count}
>
%
HANDLE SIDE EFFECTS
useEffect
useEffect(() => {
applyEffect(dependencies);
return () => cleanupEffectQ;
}, [dependencies]);¢ Class way
class FriendStatus extends React.Component {
state = { isOnline : null };
componentDidMount() {
ChatAPL.subscribeToFriendStatus(
this.props.friend.id,
this.handleStatusChange
%
}
componentWillUnmount( {
ChatAPL.unsubscribeFromFriendStatus(
‘this.props.friend.id,
this.handleStatusChange
%
}
componentDidUpdate(prevProps) {
if(this.props.friend.id !== prevProps.id) {
ChatAPL.unsubscribeFromFriendStatus(
prevProps.friend.id,
this.handleStatusChange
%
ChatAPL.subscribeToFriendStatus(
‘this.props.friend.id,
this.handleStatusChange
4
i
}
handleStatusChange = status => {
this.setState({
isOnline: status.isOnline
Ds
+
render() {
if (his.state.isOnline
return ‘Loading.
null) {
y
return this.state.isOnline ? ‘Online’ : ‘Offline’;
}« Hook Way
import { useState, useEffect } from ‘react’;
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
status
const handleStatusChange = (status) => setIsOnline(status.isOnline);
useE ffect(
O=>{
// Update status when the listener triggers
ChatAPL.subscribeToFriendStatus(
props.friend.i
handleStatusChange
»
// Stop listening to status changes every time we cleanup
return function cleanupQ {
ChatAPL.unsubscribeFromFriendStatus(
props.friend.id,
handleStatusChange
%
‘
b
[props.friend.id] // Cleanup when friend id changes or when we "unmount"
if (isOnli null) {
return ‘Loading...
+
return isOnline ? ‘Online’ : ‘Offline’;
}
useLayoutEffect
useLayoutEffect(() => {
applyBlockingEffect(dependencies);
return cleanupEffectQ;
}, [dependencies]);useLayoutEffect is almost same as useEffect, but fires
synchronously after the render phase. Use this to safely read from
or write to the DOM
import { useRef, useLayoutEffect } from "react";
function ColoredComponent({color}) {
const ref = useRefQ);
useLayoutEffect(Q) => {
const refColor = ref.currentstyle.color;
console.log(" ${refColor} will always be the same as ${color}");
ref.current.style.color = "rgbba(255,0,0)";
}; [color];
useE ffect(() => {
const refColor = ref.current.style.color;
console log
“but ${refColor} can be different from ${color} if you play with the
Dom
»
}; [color];
return (
Hello React hooks !
%
}
// tgb(42, 13, 37) will always be the same as rgb(42, 13, 37)
// but rgb(255, 0, 0) can be different from rgb(42, 13, 37) if you play with the DOMUSE THE CONTEXT API
useContext
const ThemeContext = React.createContextQ;
const contextValue = useContext(ThemeContext);
¢ Class way
class Header extends React.Component {
public render() {
return (
{({ handleLogin, isLoggedIn}) => (
{({ isOpen, showModal, hideModal }) => (
{({ notification, notify }) => {
return (
)
y
a
>
%
+¢ Hook Way
import { useContext } from ‘react’;
function HeaderQ) {
const { handleLogin, isLoggedIn} = useContext(AuthContext);
const { isOpen, showModal, hideModal } = useContext(ModalContext);
const { notification, notify } = useContext(NotificationContext);
return...
}
NOTE: Use the created context, not the consumer.
const Context = React.createContext(defaultValue);
// Wrong
const value = useContext(Context.Consumer);
// Right
const value = useContext(Context);
MEMOIZE EVERYTHING
useMemo
const memoizedValue = useMemo (
Q => expensiveFn (dependencies),
[dependencies]function RandomColoredLetter(props) {
const [color, setColor] = useState(‘#fff)
const [letter, setLetter] = useState(‘a’)
const handleColorChange = useMemo(() => () =>
setColor(randomColor0), [1
const handleLetterChange = useMemo(() => () =>
setLetter(randomColor(), []);
return (
)
}USE REFS
useRef
const ref = useRefQ;
useRef can just be used as a common React ref :
import { useRef } from "react";
function TextInput( {
const inputRef = useRef(null);
const onBtnClick = () => inputRef.current.focusQ);
return (
°
>
But it also allows you to just hold a mutable value through any
render. Also, mutating the value of ref.current will not cause any
render.
useImperativeHandle
useImperativeHandle (
ref,
createHandle,
[dependencies]useImperativeHandle allows you to customize the exposed interface
of a component when using a ref. The following component will
automatically focus the child input when mounted :
function TextInput(props, ref) {
const inputRef = useRef(null);
const onBtnClick = Q => inputRef.current.focusQ;
useImperativeHandle(ref, () => ({
focusInput: () => inputRef.current.focus(;
Ds
return (
)
}
const TextInputWithRef = React.forwardRef(TextInput);
function Parent {
const ref = useRef(null);
useEffect(Q => {
ref.focusInput0;
+s
return (
%REUSABILITY
Extract reusable behaviour into custom hooks.
import { useState, useRef, useCallback, useEffect } from "React";
//\et's hide the complexity of listening to hover changes
function useHover() {
const [value, setValue] = useState(false); // store the hovered state
const ref = useRef(null); // expose a ref to listen to
// memoize function calls
const handleMouseOver = useCallback(() => setValue(true), [);
const handleMouseOut = useCallback(() => setValue(false), []);
// add listeners inside an effect,
// and listen for ref changes to apply the effect again
useEffect(() => {
const node = ref.current;
if (node) {
node.addEventListener("mouseover", handleMouseOver);
node.addEventListener("mouseout", handleMouseOut);
return Q => {
node.removeEventListener(mouseover", handleMouseOver);
node.removeEventListener("mouseout", handleMouseOut);
k
}
}, [ref.current);
// return the pair of the exposed ref and it's hovered state
return [ref, value];
const HoverableComponent = () => {
const [ref, isHovered] = useHover();
return (
%
red” )} ref={ref}>
i