Harry React CheatSheet
Harry React CheatSheet
JS
CHEATSHEET
REACT HOME
What is ReactJS?
ReactJS is a JavaScript library used to build User Interfaces(UI). It
significantly decreases the code with it's components, states i.e.
hooks, etc.
Copy
OR, you can directly make your application without specifying a
name, like this:
npx create-react-app .
Copy
In this case, all files will be kept in the current directory.
Note: When choosing folder name, make sure there are no spaces
or capital letters because of npm naming restrictions.
Once base application is created, if folder specified you just have
to enter the folder. You can use this command to enter:
cd directory-name
Copy
Then just start up the application with this command:
npm start
Copy
and you are good to go!
Hello World
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
Copy
In this we are just putting <h1> tag in a div with id 'root'. That's it!
In div with id 'root' everything will be rendered. We can also
change it from 'root' to something else, as we are just getting an
element and putting HTML in it.
REACT ES6
What is ES6?
ES6 stands for ECMAScript 6. ECMAScript is a JavaScript standard
intended to ensure a common language across different browsers.
ES6 is the 6th version of ECMAScript.
Arrow Functions:
Copy
or
Copy
.map(): .map can be used for alot of things, one of it's use
case is, we can make any number of cards through loop
and just put it in jsx, like this:
Copy
Destructuring:
Old Way:
Copy
New Way:
Copy
Copy
Example:
Copy
Spread Operator:
Copy
Output:
["JS","Python","Java","C","C++","C#"]
Copy
and many more like, classes, modules.
ReactDOM.render()
This function takes two arguments, HTML content which you want
to show on page and HTML element where you want to put the
HTML content(first argument).
But where will it find that element? It will find it inside "index.html"
located in "public" folder. There you will notice a div with id "root".
That is where all this will be rendered!
ReactDOM.render(<p>Hello</p>,
document.getElementById('root'));
Copy
REACT JSX
What is JSX?
JSX stands for JavaScript XML. It is similar in appearance to HTML,
hence provides a way to easily write HTML in react.
Coding in JSX
Earlier we had to make an HTML element or append it into existing
ones with methods like createElement() / appendChild()
Copy
Now we can just do it directly, like this:
Copy
Expressions in JSX
You can write the expression in {}
You can write simple mathematical operations to variable to states
to complicated operations with ternary operators and it will return
the result, like:
Mathematical Operations:
Copy
Variables/States:
Copy
Ternary Operators:
REACT COMPONENT
There are two types of components:
Copy
it also requires a render method which returns HTML.
function Cat() {
return <h1>Meow</h1>;
}
Copy
Note: Component's name must start with uppercase letter.
Rendering a Component
We made a component, now we want to render/use it. Syntax for
using a component is:
<ComponentName />
Copy
Components in Files
To have less mess inside main file(with all the components in the
same file) and to resuse components on different pages, we have
to make them separately. So that we can just import them in any
file and use them!
For that we will just make a new file called Cat.js, make class or
function based component there and export default that
class/function! Like this:
function Cat() {
return <h1>Meow</h1>;
}
Copy
Note: File name must start with uppercase letter.
Props
As mentioned earlier, we can import the same component in
different files and use it, but maybe in different files some changes
in the component is needed. For that, we can use props! Like this:
Component:
function Cat(props) {
return <h1>Meow's color is {props.color}</h1>;
}
Copy
Main file:
REACT CLASS
Copy
it also requires a render method which returns HTML.
Note: Component's name must start with uppercase letter.
Component Constructor
Constructor gets called when the component is initiated. This is
where you initiate the component's properties. In React we have
states which update on page without reload. Constructor
properties are kept in state.
We also need to add super() statement, which executes the
parent component's constructor and component gets access to all
the functions of the parent component, like this:
REACT PROPS
Props are arguments passed to React components via HTML attributes.
Example:
Component:
function Cat(props) {
return <h1>Meow's color is {props.color}</h1>;
}
Copy
Main file:
Copy
Output:
REACT EVENTS
If you have coded even a little bit in javascript, you know the
importance of events.
Events
Every HTML attribute in React is written in camelCase syntax.
Event is also an attribute. Hence, written in camelCase.
As we learnt variables, states, javascript operations are written in
curly braces {}, same is true with React event handlers too! Like
this: onClick={show}
<button onClick={show}>Show</button>
Copy
Arguments in events
We can't pass arguments just like that, it will give syntax error.
First, we need to put the whole function in arrow function, like this:
Copy
REACT CONDITION
React Conditional
One of the best thing in React is in React we can conditionally
render elements/components!
&& Operator
This is one of the way to conditionally render:
function App() {
const loading = true;
return (
<div className="App">
{loading && <LoadingGif />}
{!loading && <Content />}
</div>
);
}
Copy
Here we are saying if loading is true then
show <LoadingGif /> and in second line, we said !loading so
that returns false in this case so <Content /> will not load and
first statement is true so <LoadingGif /> will load!
Ternary Operator
What we were doing in previous example was basically
just if statement. We don't have else so we were
using if as else too. Let's learn how to do both(if/else)!
Same thing can be done like this:
function App() {
return (
<div className="App">
{loading ? <LoadingGif /> : <Content />}
</div>
);
}
Copy
We are saying if loading is true then show <LoadingGif />, else
show <Content />, simple!
Syntax:
REACT LISTS
In React we render lists with loop
map()
An example of map:
function App() {
const languages = ['JS', 'Python', 'Java', 'C', 'C++',
'C#'];
return (
<div className="App">
{languages.map((language) => {
return <div>I love {language}</div>
})}
</div>
);
}
Copy
Output:
Keys
With keys React keep record of elements. This ensures that if an
item is updated or removed, only that item will be re-rendered
instead of the entire list. Example:
function App() {
const languagesDict = [
{ id: 1, language: 'JS' },
{ id: 2, language: 'Python' },
{ id: 3, language: 'Java' },
{ id: 4, language: 'C' },
{ id: 5, language: 'C++' },
{ id: 6, language: 'C#' }
];
return (
<div className="App">
{languagesDict.map((language) => {
return <div key={language.id}>
{language.id}. {language.language}
</div>
})}
</div>
);
}
Copy
Output:
REACT FORMS
React Forms are mostly like normal HTML forms, except we
use state in this to handle inputs.
Handling Forms
In React all the data is handled by component and stored in
component state. We can change state with event handlers in
the onChange attribute, like this:
import { useState } from 'react';
function Form() {
const [email, setEmail] = useState('');
return (
<form>
<label>
Enter your email: <input type="email"
value={email} onChange={(e) =>
setEmail(e.target.value)} />
</label>
</form>
)
}
Copy
Submitting Form
We can submit form with onSubmit attribute for the <form>
function Form() {
const [email, setEmail] = useState('');
return (
<form onSubmit={handleSubmit}>
<label>
Enter your email: <input type="email"
value={email} onChange={(e) =>
setEmail(e.target.value)} />
</label>
<input type="submit" />
</form>
)
}
Copy
Multiple Inputs
We don't have to make multiple states for multiple inputs, we can
save all values in one, like this:
function Form() {
const [data, setData] = useState({});
return (
<form onSubmit={handleSubmit}>
<label>
Enter your email: <input type="email"
name='email' value={data.email}
onChange={handleChange} />
</label>
<label>
Enter your name: <input type="text" name='name'
value={data.name} onChange={handleChange} />
</label>
<input type="submit" />
</form>
)
}
Copy
Here in handleChange we used Spread Operators. We are
basically saying keep whole data as it was, just change this name's
value. Then it is saved as an object so we are getting that
by data.email and data.name.
REACT ROUTER
React Router
React router is used for page routing as React App doesn't include
it as default.
npm i -D react-router-dom
Copy
Folder Structure:
src/pages/:
Home.js
Blogs.js
Contact.js
Nopage.js
Usage
Now we will make routes in src/index.js, like this:
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
reportWebVitals();
Copy
Home.js
Make all the Navigation links using <Link> tag, like this:
Copy
Blogs.js
Copy
Contact.js
Copy
NoPage.js
Copy
This is made for any route that doesn't exist. To show 404 error
there!
REACT MEMO
By default React re-renders components again and again.
Using memo will stop that if props have not changed.
Problem
Importing memo
Copy
Using memo
Everything remains the same, just when you are exporting the
Navbar, you have to wrap it in memo, like this:
1. Inline Styling
2. CSS Stylesheets
3. CSS Modules
Inline Styling
Copy
In this first curly brace is to write javascript and second is to
make a javascript object. We can also write it like:
const h1Style = {
backgroundColor: 'purple',
color: 'white'
}
return (
<>
<h1 style={h1Style}>CodeWithHarry</h1>
</>
);
}
Copy
Note: CSS property name must be camelCase. background-
color would be backgroundColor
CSS Stylesheets
You can save the whole CSS in a separate file with file
extension .css and import it in your application.
App.css
body {
background-color: 'purple';
color: 'white';
}
Copy
Here we are writing CSS, so we don't need to make JS Object or
do it in camelCase.
Index.js
Just import it like this:
import './App.css'
Copy
CSS Modules
.button {
background-color: 'purple';
color: 'white';
}
Copy
Import it in component like this:
REACT HOOKS
Hooks were added to React in version 16.8. Hooks let you use
state and other React features without writing a class.
Although states have largely replaced classes in React, there is no
plan of removing classes from React.
Things you need to keep in mind while using hooks:
// import statements
// Can't call here
const Blogs = () => {
// Can call here
return <h1>Blogs</h1>;
};
Copy
REACT USESTATA
useState is a Hook that lets you add React state to function
components.
Importing useState
To use useState, first we need to import useState and initialize
it, you can import it from react like this:
Copy
Initializing useState
You can initialize state like this:
Copy
useState takes initial state as argument and gives a state and
a function(setName in this case) to update that state as we can't
directly change/update a state. Also, these state names are just
like variables, hence you can name them anything you like.
Reading a state
Copy
Updating a state
Copy
What can state hold?
Like normal variables, state can hold any datatype like strings,
numbers, booleans, arrays, objects, objects in arrays, arrays in
objects. For example:
Copy
Updating Objects and Arrays in State
Copy
REACT USEEFFECT
The useEffect Hook allows you to perform side effects in your
components.
useEffect accepts two arguments. The second one is optional.
Runs on every render:
function Home() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
});
Copy
Runs on first render:
function Home() {
const [count, setCount] = useState(0);
useEffect(() => {
setTimeout(() => {
setCount((count) => count + 1);
}, 1000);
}, []);
Copy
Runs when data changes:
function Home() {
const [count, setCount] = useState(0);
const [data, setData] = useState('');
const handleChange = (e) => {
setData(e.target.value)
}
useEffect(() => {
setCount((count) => count + 1);
}, [data]);
REACT USECONTEXT
useState is a Hook that lets you add React state to function
components. useContext helps to manage states globally, i.e.
between components.
Problem
Copy
Context Provider
Now we need to wrap the component tree that need the state
Context in a Provider. It's like the Provider will provide the state
to every component in that tree which is wrapped in Provider.
function App() {
const [state, setState] = useState('true');
return (
<StateContext.Provider value={state}>
<h1>{`Hi! My state is ${state}!`}</h1>
<Home state={state} />
</StateContext.Provider>
);
}
Copy
useContext hook
First we need to import it:
Copy
To access useContext, you can do something like this:
function Home() {
const state = useContext(StateContext);
return (
<>
<h2>{`Hii! My state is ${state}! `}</h2>
</>
);
}
REACT USEREF
useRef keeps the value stored between renders.
In this, value changed doesn't cause a re-render.
It can also be used to access a DOM element directly.
Doesn't cause re-render
function App() {
const [stateValue, setStateValue] = useState("");
const refValue = useRef("");
return (
<>
</>
);
}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Copy
In this, if you click on state button, state will update and it will
re-render, whereas if you click on ref, nothing visible will
happen, i.e. ref will change but it won't re-render. To verify
this, you can again click on state, it will again update and re-
render but this time ref has some value stored, so that will
display.
function App() {
const inputElement = useRef();
return (
<>
<input type="text" ref={inputElement} />
<button onClick={focusInput}>Focus Input</button>
</>
);
}
const root =
ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
Copy
In this, we initialized a useRef. In jsx, we used an attribute
called ref to store reference, once we have reference then we
can use it anyway we want.
REACT USEREDUCER
useReducer is similar to useState hook.
It lets you write your custom state logic.
It lets you pass dispatch down instead of callbacks resulting in
optimized performance for components that trigger deep
updates.
When to use useReducer?
Copy
Here reducer is a function which contains your custom state
logic and initialState is as name suggests, it's initial state.
As you can see useReducer returns the current state and
a dispatch method.
Here is an example:
const initialData = {
lowercase: '',
uppercase: '',
spaces: ''
}
REACT USECALLBACK
REACT USECALLBACK
React useCallback Hook returns a memoized callback function.
It is done so that it does not need to be recalculated resulting in
improved performance.
If we don't use useCallback function would run on every render.
This helps us to memoize resource intensive functions so that
they will not automatically run on every render.
With useCallback Hook, memoized function only runs when any
of its dependencies update.
When to use useCallback?
You may think we can use memo and stop a component from re-
rendering but if there is a case where you are passing a
function as prop to a component, then it will re-render
irrespective of memo. It is because of something called
"referential equality". In this every time a component re-
renders, its function gets recreated. Hence, memo is working but
because function is getting recreated, component will re-render.
To avoid this, we can use useCallback!
Like this:
Copy
Like this we are memoizing the function and only letting it run
when the dependency state changes!
REACT MEMO
React useMemo Hook returns a memoized value.
It is similar to useCallback Hook. The main difference
is useMemo returns a memoized value and useCallback returns
a memoized function.
The useMemo Hook only runs when any of its dependencies
update.
useMemo can improve performance big time.
When to use it?
Copy
This function will run on every render resulting in slowing down
of everything. To prevent this, we can memoize it's result and
return it without calculating and only recalculate it when num
changes.
For this we will make a state number because we have to give
changing factor as dependency. Hence, code would be: