ReactJS
Cheatsheet
Pixaflip Technologies
Basic Concepts
React is a JavaScript library for building
user interfaces.
● React uses a virtual DOM to update
the UI, making it fast and scalable.
● React allows you to create reusable
UI components.
//Basic React App
import React from 'react';
import ReactDOM from 'react-dom';
function App() {
return (
<div>
<h1>Hello, world!</h1>
<p>This is a paragraph.</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
JSX
● JSX is a syntax extension for JavaScript
that allows you to write HTML-like
syntax within your code
const element = <h1>Hello, world!</h1>; //JSX
02
Components
Components are the building blocks of
React applications.
● There are two types of components
in React: function components and
class components.
.
//Functional Component
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
//Class Component
class Greeting extends React.Component {
render() {
return <h1>Hello, {this.props.name}!</h1>;
}
}
Props
● Props are used to pass data from a
parent component to a child
component
03
function User(props) {
return (
<div>
<p>{props.name}</p> // It will print “John Doe”
</div>
);
}
ReactDOM.render(
<User name="John Doe"/>,
document.getElementById('root')
);
React Hooks
React Hooks are a set of functions that
allow functional components to have
state, lifecycle methods,
1. useState
● Allows you to add state to functional components in React.
● Returns a stateful value and a function to update it.
const [state, setState] = useState(initialState); //declaring state
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
//Updating State
2. useEffect
● Allows you to use lifecycle methods in functional components in React.
● Runs side effects after every render, or only when certain dependencies
change.
useEffect(() => {
// Side effects go here
}, [dependencies]);
04
3. useReducer
● Allows you to manage complex state in functional components in
React.
● Returns a stateful value and a function to update it based on actions.
const [state, dispatch] = useReducer(reducer, initialState);
4. useMemo
● Memoizes a value to prevent unnecessary re-computations in React.
● Returns a memoized value.
const memoizedValue = useMemo(() => {
doExpensiveComputation(a, b);
}, [a, b]);
5. useRef
● Allows you to create a mutable ref object in React.
● Returns a ref object that persists for the lifetime of the component.
const refContainer = useRef(initialValue);
6. useContext
● Allows you to use context in functional components in React.
● Returns the current context value for a given context.
const value = useContext(MyContext);
7. useCallback
● Memoizes a function to prevent unnecessary re-renders in React.
● Returns a memoized version of the function.
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);
05