React Complete Guide With Theory and Examples v2
React Complete Guide With Theory and Examples v2
1. What is React?
React is an open-source JavaScript library created by Facebook for building fast and interactive user
interfaces. It is primarily used for developing single-page applications where data changes over time. Instead
of manipulating the DOM directly, React uses a virtual DOM to efficiently update only the parts that need to
change.
Key Features:
- Virtual DOM: Minimizes direct manipulation of the DOM for better performance.
- Learn Once, Write Anywhere: Can be used for web, mobile (React Native), and desktop (Electron).
Example:
function Welcome(props) {
To start a React project, you can use Create React App or Vite.
cd my-app
npm start
cd my-app
npm install
These commands set up the folder structure, install dependencies, and run a local development server.
3. Understanding JSX
JSX (JavaScript XML) is a syntax extension for JavaScript used with React to describe what the UI should
Rules:
Example:
4. Components
Functional Component:
function Greet(props) {
render() {
Props (short for properties) are used to pass data from one component to another.
Example:
State is a built-in object used to store property values that belong to a component.
useState Hook:
State allows components to react to user input and change the UI accordingly.
6. useEffect Hook
The useEffect hook is used to perform side effects such as fetching data, setting up subscriptions, or
Example:
useEffect(() => {
React Complete Beginner Guide with Theory and Examples
console.log("Component mounted");
}, []);
The empty array means this effect runs only once (on mount).
7. Conditional Rendering
Example:
Example:
<li key={index}>{item}</li>
))}
The 'key' prop is important to help React identify which items have changed.
React uses controlled components where form data is handled by React state.
Example:
This ensures the component always has the latest value from the input.
useRef is a hook that allows you to directly access a DOM element or persist values between renders without
causing re-renders.
Example:
The useContext hook allows you to use global variables like themes or user info without prop drilling.
Example:
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
React Complete Beginner Guide with Theory and Examples
Install it with:
Example:
<BrowserRouter>
<Routes>
</Routes>
</BrowserRouter>
You can use fetch inside useEffect to retrieve data from an API.
Example:
useEffect(() => {
fetch("https://api.example.com/data")
}, []);
Example:
<Suspense fallback={<div>Loading...</div>}>
<LazyComp />
</Suspense>
17. Deployment
React apps are SPA (single page applications), so configure rewrites properly.