React Concepts With Code
React Concepts With Code
1. Virtual DOM
// Explanation:
// The Virtual DOM is a lightweight JavaScript representation of the actual DOM.
// React updates the Virtual DOM first and then efficiently updates the real DOM.
// Example:
function App() {
return <h1>Hello, Virtual DOM!</h1>;
}
2. useState Hook
// Explanation:
// useState allows functional components to have state.
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
3. useEffect Hook
// Explanation:
// useEffect runs side effects like fetching data, subscriptions, or manually changing
the DOM.
import React, { useState, useEffect } from 'react';
function Timer() {
const [count, setCount] = useState(0);
useEffect(() => {
const interval = setInterval(() => {
setCount(c => c + 1);
}, 1000);
5. useMemo Hook
// Explanation:
// useMemo caches computed values to prevent unnecessary recalculations.
6. useCallback Hook
// Explanation:
// useCallback memoizes a function to prevent unnecessary re-creation.
function App() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<Button onClick={handleClick} />
</div>
);
}
7. useSuspense Hook
// Explanation:
// Suspense is used for lazy loading components.
// Explanation:
// Redux follows a unidirectional data flow:
// Action -> Reducer -> Store -> View (Component).
// Example:
import { createStore } from 'redux';