0% found this document useful (0 votes)
3 views

ReactJS

The document provides a comprehensive overview of ReactJS and React Native, covering installation, main concepts, JSX, rendering elements, components, state management, event handling, conditional rendering, lists, accessibility, code-splitting, context, error boundaries, hooks, and advanced topics. Each section includes practical examples to illustrate the concepts. It serves as a guide for developers to understand and implement React effectively.

Uploaded by

RAVI TEJA C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ReactJS

The document provides a comprehensive overview of ReactJS and React Native, covering installation, main concepts, JSX, rendering elements, components, state management, event handling, conditional rendering, lists, accessibility, code-splitting, context, error boundaries, hooks, and advanced topics. Each section includes practical examples to illustrate the concepts. It serves as a guide for developers to understand and implement React effectively.

Uploaded by

RAVI TEJA C
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

ReactJS

Here's a detailed explanation of each ReactJS and React Native topic with examples.

1. Installation
ReactJS is installed using create-react-app :

npx create-react-app my-app


cd my-app
npm start

React Native is installed using Expo CLI:

npx create-expo-app my-app


cd my-app
npm start

React Native CLI requires Android Studio for emulator setup.


Dependencies like react , react-dom , and react-native must be installed.
Babel and Webpack compile JSX and optimize the app.
Hot-reloading is enabled for instant UI updates.
React Native apps can be tested on real devices via Expo Go.
React apps use package.json to manage dependencies.
React development requires Node.js for running scripts.

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" />

3. JSX (JavaScript XML)


JSX allows writing HTML-like syntax inside JavaScript.
It improves readability and works with React’s rendering engine.
Must be enclosed inside a single parent element.
Supports JavaScript expressions inside {} .
Attributes are written in camelCase ( className instead of class ).
Can call functions and use variables inside JSX.
Conditional rendering is supported using ternary operators.
JSX is compiled by Babel into JavaScript.
JSX elements are immutable (cannot be changed directly).
Fragment ( <> </> ) avoids unnecessary <div> wrappers.

Example:

const name = "Amudesh";


const element = <h1>Hello, {name}!</h1>;

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:

const element = <h1>Welcome to React!</h1>;


ReactDOM.createRoot(document.getElementById('root')).render(element);

5. Components and Props


Components are reusable UI blocks in React.
They can be functional or class-based.
Props (short for properties) allow data to be passed between components.
Props are immutable (cannot be changed inside child components).
Functional components receive props as function parameters.
Default props can be assigned if none are provided.
Props allow customization of components dynamically.
Parent components pass props to children like attributes.
Components can return multiple JSX elements inside fragments.
React encourages reusability through props and components.

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:

function Greeting({ isLoggedIn }) {


return <h1>{isLoggedIn ? "Welcome back!" : "Please sign in."}</h1>;
}

9. Lists and Keys


Lists allow rendering multiple components dynamically.
.map() is used to iterate over arrays and return JSX elements.
Each list item must have a unique key for efficient rendering.
Keys help React track changes and improve performance.
Keys should be unique but stable, avoiding array indexes if possible.
List items can be extracted into separate components.
React efficiently updates only the changed elements in lists.
key helps avoid unnecessary re-renders.
Helps in rendering dynamic content like menus, user lists, etc.
Used in rendering data from APIs dynamically.

Example:

const names = ["Amudesh", "Stark", "Nivi"];


const listItems = names.map((name) => <li key={name}>{name}</li>);
return <ul>{listItems}</ul>;

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:

<button aria-label="Submit Form">Submit</button>

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:

const LazyComponent = React.lazy(() => import('./MyComponent'));

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:

const ThemeContext = React.createContext('light');

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:

class ErrorBoundary extends React.Component {


constructor(props) {
super(props);
this.state = { hasError: false };
}

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>;
}

15. Advanced ReactJS Topics


Server-Side Rendering (SSR): Improves SEO and load time (Next.js).
Static Site Generation (SSG): Pre-renders pages at build time (Gatsby).
Progressive Web Apps (PWA): Offline-first approach with service workers.
State Management: Using Redux, Recoil, Zustand for scalable apps.
React Fiber: Reconciliation engine for faster UI updates.
GraphQL Integration: Fetch data efficiently with Apollo Client.
React Testing Library: Ensures UI behaves correctly.
Performance Optimization: Using memoization ( useMemo() , useCallback() ).
Micro Frontends: Break large apps into smaller independent units.
WebAssembly (WASM): Running high-performance code inside React.

You might also like