ReactJS
ReactJS
Here's a detailed explanation of each ReactJS and React Native topic with examples.
1. Installation
ReactJS is installed using create-react-app :
2. Main Concepts
React is component-based, meaning UI is broken into reusable pieces.
Virtual DOM updates only the necessary parts of the UI efficiently.
Uses a unidirectional data flow (from parent to child components).
JSX is used to write HTML inside JavaScript.
Components can be functional or class-based.
Props allow data transfer between components.
State manages dynamic data inside components.
Events are handled differently from vanilla JavaScript.
React follows a declarative UI approach, making code predictable.
Components re-render when state changes.
Example:
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Welcome name="Amudesh" />
Example:
4. Rendering Elements
Rendering displays UI components inside the DOM.
React updates only the changed elements efficiently.
Uses ReactDOM.createRoot().render() in React 18.
Components can be re-rendered when state or props change.
setState() in class components and useState() in functional components trigger re-
rendering.
Lists can be dynamically rendered using .map() .
Conditional rendering can be done using ternary operators.
React components must return a single root element.
React.StrictMode helps identify potential problems.
Rendering can be optimized using memoization (React.memo).
Example:
Example:
function Greeting(props) {
return <h1>Hello, {props.name}!</h1>;
}
<Greeting name="Stark" />
6. State and Lifecycle
State holds data that affects rendering.
Unlike props, state is mutable and can be updated.
useState is used in functional components for state management.
Class components use setState() to update state.
Lifecycle methods like componentDidMount() handle initialization.
componentDidUpdate() runs when component updates.
componentWillUnmount() cleans up resources.
useEffect() is used for handling side effects in functional components.
State updates trigger component re-rendering.
React follows a three-phase lifecycle model: Mounting, Updating, Unmounting.
Example:
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}
7. Handling Events
Events in React use camelCase ( onClick , onChange ).
Use function references instead of inline event handlers.
Arrow functions are commonly used for event handling.
Prevent default actions using event.preventDefault() .
Class components use .bind(this) for event handling.
Functional components handle events more simply.
Synthetic events wrap browser events for cross-browser compatibility.
Events can be passed as props to child components.
Conditional event handling can be done inside functions.
Events are automatically handled in the Virtual DOM.
Example:
function Button() {
function handleClick() {
alert("Button clicked!");
}
return <button onClick={handleClick}>Click Me</button>;
}
8. Conditional Rendering
Components can render different UI based on conditions.
The ternary operator is commonly used: {condition ? <Component1 /> : <Component2
/>} .
if-else can be used inside render functions.
The && operator is used for short-circuit rendering.
Components can return null to prevent rendering.
Useful for authentication-based UI (login/logout states).
Helps dynamically show or hide components.
Prevents unnecessary rendering using lazy loading.
Can be combined with React Router for conditional navigation.
Simplifies UI state management efficiently.
Example:
Example:
10. Accessibility
Ensures apps are usable by everyone, including disabled users.
Uses ARIA attributes ( aria-label , role , etc.) to improve accessibility.
HTML elements like <button> and <input> have built-in accessibility.
Semantic HTML ( <nav> , <article> , <section> ) improves screen reader support.
alt attributes should be used for images.
Keyboard navigation ( tabindex , onKeyDown ) must be considered.
focus() and blur() manage focus for accessibility.
Tools like Lighthouse and axe-core help test accessibility.
React’s useRef helps manage focus dynamically.
Enhances user experience for diverse audiences.
Example:
11. Code-Splitting
Helps reduce initial bundle size by loading only needed code.
Improves performance by lazy-loading components.
React’s React.lazy() and Suspense allow dynamic imports.
Useful for large applications with many routes.
Prevents blocking the main thread with unnecessary code.
Works well with Webpack’s code-splitting feature.
Can load components only when needed (e.g., modal popups).
Server-side rendering (SSR) can optimize further.
Reduces time to interactive (TTI) for better user experience.
Improves mobile and low-network performance.
Example:
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
12. Context
Context API helps avoid prop-drilling in deeply nested components.
Provides a global state management solution for small apps.
Uses React.createContext() and useContext() hooks.
Good for managing theme, authentication, language settings, etc.
Provider wraps components that need the shared state.
Consumer (or useContext ) accesses the context value.
Better alternative than passing props manually through multiple levels.
Reduces re-renders by optimizing context updates.
Not a replacement for Redux but useful for simpler state management.
Helps maintain a clean and maintainable codebase.
Example:
function ThemedButton() {
const theme = useContext(ThemeContext);
return <button className={theme}>Click Me</button>;
}
13. Error Boundaries
Catches JavaScript errors inside child components.
Prevents UI from crashing by displaying a fallback UI.
Implemented using componentDidCatch() in class components.
Helps in debugging issues during rendering.
Cannot catch errors inside event handlers.
Used for logging errors to monitoring services (Sentry, LogRocket).
Useful in handling errors from third-party libraries.
React provides built-in tools like React DevTools for debugging.
Helps maintain user experience by preventing complete UI failure.
Functional components can use ErrorBoundary HOCs for error handling.
Example:
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
14. Hooks
Hooks allow state and lifecycle management in functional components.
Eliminates the need for class components in most cases.
The most common hooks are useState() and useEffect() .
Hooks cannot be used inside loops or conditions.
Custom hooks ( useCustomHook ) allow code reusability.
React provides built-in hooks for context, refs, memoization, etc.
useReducer() is an alternative to Redux for state management.
Hooks follow the Rules of Hooks for consistency.
Simplifies code structure and readability.
Improves performance by reducing unnecessary re-renders.
Example:
function Counter() {
const [count, setCount] = useState(0);
return <button onClick={() => setCount(count + 1)}>Count: {count}</button>;
}