React Basic Concepts
What is React?
React is a JavaScript library used to build user interfaces (UI).
Key Features
Component-based architecture
Reusable code
Fast rendering using Virtual DOM
Easy to manage large applications
Key Features of React
1. Component-Based Architecture
React applications are built using components. A component is a small, reusable piece of UI.
function Welcome() {
return <h1>Hello User</h1>;
}
2. Virtual DOM (Fast Performance)
React uses a Virtual DOM, which is a lightweight copy of the real DOM. Instead of updating the entire page, React:
Updates only the changed parts
Makes the application faster
3. Reusability
Components can be reused multiple times, which:
Reduces code duplication
Makes development faster
4. Declarative UI
React uses a declarative approach, meaning: You describe what the UI should look like, and React updates it automatically.
What is JSX?
JSX stands for JavaScript XML. It allows us to write HTML-like code inside JavaScript.
const element = <h1>Hello World</h1>;
Looks like HTML but it is actually JavaScript
Makes code easier to read and write
Used to describe UI
JSX with JavaScript
Use {} to write JavaScript inside JSX.
const name = "John";
const element = <h1>Hello {name}</h1>;
Rules of JSX
- Must return a single parent element
// Wrong
return (
<h1>Hello</h1>
<p>World</p>
);
// Correct
return (
<div>
<h1>Hello</h1>
<p>World</p>
</div>
);
Use
classNameinstead ofclassUse
{}for JavaScript expressions
What is Babel?
Babel is a JavaScript compiler. It converts JSX into normal JavaScript that browsers can understand.
// JSX (what you write)
const element = <h1>Hello</h1>;
// After Babel conversion (what browser reads)
const element = React.createElement("h1", null, "Hello");
Browsers do NOT understand JSX directly
Babel converts JSX to JavaScript automatically
Makes React work in all browsers
Virtual DOM vs Real DOM in React
What is Real DOM?
The Real DOM (Document Object Model) is the actual structure of a web page. It represents HTML elements as a tree structure in the browser.
<body>
<h1>Hello</h1>
<p>World</p>
</body>
Problem with Real DOM:
Updating it is slow
Even small changes can re-render large parts of the UI
Causes performance issues
What is Virtual DOM?
The Virtual DOM is a lightweight copy of the Real DOM. It exists in memory, not directly in the browser.
How Virtual DOM Works
React creates a Virtual DOM
When state changes, a new Virtual DOM is created
React compares old vs new Virtual DOM (Diffing)
Only the changed parts are updated in the Real DOM
Components in React
A component is a small, reusable piece of UI in React. Every React application is built by combining multiple components.
function Welcome() {
return <h1>Hello User</h1>;
}
Components are reusable
Each component manages its own logic
UI is divided into small independent parts
Functional vs Class Components
Class Component
Based on ES6 classes
Uses
this.statefor stateUses lifecycle methods (
componentDidMount, etc.)Requires
thiskeywordMore boilerplate code
class Counter extends Component {
state = { count: 0 };
render() {
return (
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Count: {this.state.count}
</button>
);
}
}
Functional Component
Plain JavaScript function
Uses Hooks for state and lifecycle
No
thiskeywordSimple and clean code
Preferred in modern React
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Count: {count}
</button>
);
}
React Hooks
What are React Hooks?
Special functions to use React features in functional components
Introduced in React 16.8
No need to write class components
Rules:
Call Hooks only at the top level
Call Hooks only inside functional components
useState
Manages local state in a component
Returns current value and a setter function
State change triggers re-render
const [count, setCount] = useState(0);
<button onClick={() => setCount(count + 1)}>Click: {count}</button>
useEffect
Runs side effects after render (API calls, timers, DOM updates)
Replaces lifecycle methods
// Runs once on mount
useEffect(() => {
console.log("Mounted");
}, []);
// Runs when count changes
useEffect(() => {
console.log(count);
}, [count]);
// Cleanup on unmount
useEffect(() => {
const timer = setInterval(() => {}, 1000);
return () => clearInterval(timer);
}, []);
| Dependency | When it runs |
|---|---|
| No array | Every render |
[] |
Once on mount |
[value] |
When value changes |
useRef
Access DOM elements directly
Does not trigger re-render
const inputRef = useRef(null);
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>Focus</button>
useReducer
Alternative to
useStatefor complex stateUses actions and a reducer function
function reducer(state, action) {
if (action.type === "increment") return { count: state.count + 1 };
if (action.type === "reset") return { count: 0 };
}
const [state, dispatch] = useReducer(reducer, { count: 0 });
<button onClick={() => dispatch({ type: "increment" })}>+</button>
useContext
Share data globally without prop drilling
Works with
createContext
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Child />
</ThemeContext.Provider>
);
}
function Child() {
const theme = useContext(ThemeContext);
return <p>Theme: {theme}</p>;
}
Controlled Components, Prop Drilling & State Uplifting
Controlled Component
Input value is managed by React state.
function Form() {
const [name, setName] = useState("");
return <input value={name} onChange={(e) => setName(e.target.value)} />;
}
React controls the value
Uses
useStateRe-renders on every change
Uncontrolled Component
Input value is managed by the DOM.
function Form() {
const inputRef = useRef();
return (
<>
<input ref={inputRef} />
<button onClick={() => alert(inputRef.current.value)}>Submit</button>
</>
);
}
DOM controls the value
Uses
useRefNo re-render on change
Prop Drilling
Passing data through multiple components that don't need it.
function App() { return <Parent name="John" />; }
function Parent(props) { return <Child name={props.name} />; }
function Child(props) { return <h2>{props.name}</h2>; }
Props passed through every level
Hard to maintain
How to Avoid — useContext
const UserContext = createContext();
function App() {
return (
<UserContext.Provider value="John">
<Child />
</UserContext.Provider>
);
}
function Child() {
const name = useContext(UserContext);
return <h2>{name}</h2>;
}
Share data globally
No need to pass props at every level
State Uplifting
Move state to the parent so multiple children can share it.
function Parent() {
const [count, setCount] = useState(0);
return (
<>
<Child1 count={count} setCount={setCount} />
<Child2 count={count} />
</>
);
}
function Child1({ count, setCount }) {
return <button onClick={() => setCount(count + 1)}>+</button>;
}
function Child2({ count }) {
return <h2>Count: {count}</h2>;
}
State lives in parent
Shared with children via props
Keeps data in sync
