FSD Unit-1 Notes
FSD Unit-1 Notes
2. JSX: JSX is a syntax extension for JavaScript that allows you to write
HTML-like code within your JavaScript files. It provides a way to describe
the structure and appearance of your components. JSX code is transpiled
to regular JavaScript code using tools like Babel.
5. Props: Props (short for properties) are used to pass data from a parent
component to its child components. Props are read-only and cannot be
modified by the child components. They are an important mechanism for
creating reusable and configurable components.
7. React Hooks: Hooks are a feature introduced in React 16.8 that allow
you to use state and other React features in functional components. Hooks
provide a way to write reusable logic and manage state without using class
components. Commonly used hooks include `useState`, `useEffect`, and
`useContext`.
These are just some of the fundamental concepts in React. React has a rich
ecosystem with many additional libraries and tools that can enhance your
development experience. It's recommended to explore the official React
documentation and practice building small React applications to gain a
deeper understanding of its capabilities.
Introduc on to AJAX
7. Fetch API and Libraries: In addition to the XHR object, modern web
browsers also provide the Fetch API, which simplifies making AJAX requests
with a more modern and intuitive syntax. Additionally, there are several
JavaScript libraries, such as Axios and jQuery.ajax, that abstract away
some of the complexities of AJAX and provide additional features for
handling requests and responses.
These are some of the key functions and techniques used in AJAX for
making HTTP requests, handling responses, and managing asynchronous
communication between the client and server. Depending on your specific
requirements and the tools or libraries you choose, you may encounter
additional functions and patterns for handling AJAX operations.
React Element, React DOM
1. React Element:
- React elements are the smallest building blocks of a React application's
UI. They are plain JavaScript objects that represent the structure and
properties of a UI component.
- React elements are created using JSX or React's `createElement`
function. JSX provides a more readable and HTML-like syntax for defining
React elements, while `createElement` is the programmatic way of
creating elements.
- React elements are lightweight and immutable, meaning they cannot
be modified once created. If you need to update the UI, you create new
elements and let React handle the reconciliation process.
2. React DOM:
- React DOM is a package specifically designed for working with the DOM
(Document Object Model). It provides the tools and methods necessary to
render React elements into the browser's DOM.
- React DOM allows you to render React components and elements into
a specific DOM container, typically an HTML element like `<div>`,
`<span>`, or `<body>`.
- The `ReactDOM.render()` method is the entry point for rendering
React elements into the DOM. It takes two arguments: the React element
to be rendered and the target DOM container where the element should be
mounted.
- React DOM efficiently updates and re-renders only the necessary parts
of the UI, thanks to the use of a virtual DOM and a diffing algorithm that
calculates the minimal changes needed to reflect the updated UI state.
Overall, React elements and React DOM work together to build and manage
the UI of a React application, allowing for efficient rendering and updating
of components in response to changes in state or props.
DOM Rendering
The process of rendering and updating the DOM in React is efficient and
optimized, thanks to the virtual DOM and the diffing algorithm used by
React. This allows for responsive UI updates with minimal performance
overhead.
It's important to note that React abstracts away many of the low-level DOM
manipulation details, allowing developers to focus on building UI
components and managing application state.
First React Applica on using Create React App
To create your first React application using Create React App, you can
follow these steps:
Step 1: Install Node.js and npm (Node Package Manager) if you haven't
already. You can download and install them from the official Node.js
website: https://nodejs.org
Step 7: Open your preferred code editor and navigate to the `src` directory
inside your project. You'll find a file named `App.js`, which is the main
component of your React application. You can modify this file or create
additional components to build your application's UI.
Step 8: Explore the `src` directory to see other files and folders generated
by Create React App. It includes the `index.js` file that renders the root
component (`App.js`) into the DOM, the `index.css` file for styling, and a
`logo.svg` file for the default React logo.
Congratulations! You have created your first React application using Create
React App. Now you can start building your React components, adding
functionality, and customizing the application to suit your needs.
React with JSX , React Element as JSX
React with JSX (JavaScript XML) allows you to write HTML-like code within
your JavaScript files when developing React applications. JSX is a syntax
extension that provides a concise and intuitive way to describe the
structure and appearance of UI components.
Here are some key points to understand about React with JSX:
3. React Components: With JSX, you can define and use React
components. Components can be written as functions or classes and
encapsulate reusable UI logic. JSX makes it easy to use components by
treating them as custom HTML tags. For example:
```jsx
function Welcome(props) {
return <h1>Hello, {props.name}!</h1>;
}
5. CSS Classes and Styles: JSX allows you to specify CSS classes using the
`className` attribute, similar to HTML's `class` attribute. Inline styles
can be defined using the `style` attribute, but they are specified as
JavaScript objects. For example:
```jsx
const element = <div className="container" style={{ color: 'blue',
fontSize: '16px' }}>Hello, JSX!</div>;
```
These are just some of the features and capabilities of React with JSX. JSX
helps make the code more readable, expressive, and maintainable, as it
combines the power of JavaScript and HTML-like syntax to describe the UI
structure in React applications.
Valida ng Props with createClass
3. Define your functional component and specify the prop types using the
`PropTypes` object:
```jsx
function MyComponent(props) {
// Component logic here
}
MyComponent.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
email: PropTypes.string
};
```
With prop validation in place, React will issue warnings in the console if the
props passed to the component do not match the specified types or if
required props are missing.
Note: If you are using ES6 classes to create components, you can also
define prop types using the `static propTypes` property inside the
component class.
It's worth noting that the `createClass` method and its associated prop
validation using `getDefaultProps` and `propTypes` are considered legacy
and are no longer recommended for new projects. It's best to use modern
React patterns with functional components or ES6 classes and the `prop-
types` package for prop validation.
React JS
4. **State and Props:** State represents the data that can change within
a component, and props are the inputs passed to a component.
Components can have local state (managed within the component) and
receive props from their parent components.
6. **Hooks:** Hooks are functions that allow you to use state and other
React features in functional components. Introduced in React 16.8, they
provide a way to use state and lifecycle methods without writing a class.
The most commonly used hooks are `useState` for managing state and
`useEffect` for performing side effects.
**Props:**
- Props (short for properties) are a way to pass data from a parent
component to its child components.
- Props are read-only and should not be modified within the child
component.
- They are used to configure and customize the child components.
- Props are passed as attributes to the child component in JSX.
- To access props within a functional component, you can simply use the
props object as a parameter. In class components, props are accessed
through `this.props`.
**State:**
- State represents the internal data of a component that can change over
time.
- Unlike props, state is managed within the component itself.
- State is typically initialized in the constructor of a class component using
`this.state = { /* initial state */ }`.
- To update state, you should use the `setState` method provided by
React, which ensures proper rendering and updates of the component.
- Never modify the state directly; always use `setState` to update it
asynchronously.
- State updates may be asynchronous, so if you need to perform an action
after the state has been updated, you can pass a callback function as the
second argument to `setState` or use the `componentDidUpdate`
lifecycle method.
**Component Tree:**
- In React, the UI is structured as a component tree hierarchy.
- The root component represents the top-level component, and it contains
child components that can further contain their own child components.
- Each component in the tree has a parent component except for the root
component.
- Components communicate with each other by passing props down the
component tree.
- Changes in the state or props of a component can trigger updates in the
child components and cause re-rendering of the affected parts of the UI.
- React efficiently updates only the necessary parts of the DOM by using
the Virtual DOM and a diffing algorithm to minimize actual DOM
manipulations.
Examples:
**Props Example:**
```jsx
// ParentComponent.jsx
import React from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const greeting = 'Hello, world!';
const name = 'John Doe';
return (
<div>
<ChildComponent greeting={greeting} name={name} />
</div>
);
}
// ChildComponent.jsx
import React from 'react';
function ChildComponent(props) {
return (
<div>
<h1>{props.greeting}</h1>
<p>{props.name}</p>
</div>
);
}
```
In this example, `ParentComponent` passes the `greeting` and `name`
props to `ChildComponent`. The child component receives these props
through the `props` object and renders them.
**State Example:**
```jsx
import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
```
In this example, the `Counter` component uses the `useState` hook to
manage its internal state. The `count` state is initialized to 0, and the
`increment` function is used to update the state when the button is
clicked.
function App() {
return (
<div>
<ParentComponent>
<ChildComponent />
</ParentComponent>
</div>
);
}
```
In this example, the `App` component represents the root of the
component tree. It renders the `ParentComponent`, which in turn renders
the `ChildComponent`. The components are organized hierarchically, with
each component having a parent component except for the root component
(`App`).
These examples demonstrate how props, state, and the component tree
work in React. Props allow you to pass data from parent components to
child components, state helps manage internal data within a component,
and the component tree defines the structure and hierarchy of components
in your React application.
Components
Remember that React is a flexible library, and the best practices and
patterns can evolve over time. Stay updated with the latest documentation
and community guidelines to make the most of React's capabilities.
Stateless and Stateful Components
3. Context API:
- React's Context API allows you to create a global state that can be
accessed by multiple components without the need for explicit prop drilling.
- With Context API, you define a provider component that wraps the
components needing access to the shared state. The provider component
defines the initial state and exposes it to the child components.
- Child components can access the shared state using the `useContext`
hook or by wrapping the component with a higher-order component
(`Context.Consumer`).
- Context API is suitable for managing state that needs to be shared
across a tree of components, such as themes, authentication, or language
settings.
2. Access State:
- Components can access their state using `this.state.propertyName`.
For example, in the above component, you can access the `counter` and
`message` states using `this.state.counter` and `this.state.message`,
respectively.
3. Update State:
- React provides the `setState` method to update the state. It accepts
an object that represents the new state or a function that returns the new
state based on the previous state.
- To update the state, call `this.setState(newState)` within the
component. React will merge the new state with the existing state and re-
render the component.
- For example, to update the `counter` state:
```jsx
this.setState({ counter: this.state.counter + 1 });
```
render() {
return <button onClick={this.handleClick}>Increment</button>;
}
```
incrementCount = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
It's worth noting that with the introduction of hooks in React, functional
components with hooks can achieve the same functionality as class
components, including managing state and accessing lifecycle methods.
However, class components are still valid and can be used in existing
codebases or when specific use cases require their usage.
**Class Components:**
- Class components are JavaScript classes that extend the
`React.Component` base class provided by React.
- They are used to define components with more complex logic, state
management, and lifecycle methods.
- Class components have access to the full range of React features,
including state, lifecycle methods, and component methods.
- While functional components with hooks have gained popularity, class
components are still supported and widely used in existing React
codebases.
**`setState` Method:**
- The `setState` method is provided by React and is used to update the
state of a class component.
- It takes an object that represents the new state or a function that receives
the previous state and returns the new state.
- React uses a shallow merge to update only the specified properties of the
state object, so you don't need to include all the properties in each call to
`setState`.
- `setState` is an asynchronous operation, meaning that React batches
multiple `setState` calls together and updates the state in an optimized
manner for performance reasons.
- To perform actions after the state has been updated, you can provide a
callback function as the second argument to `setState`.
- It's important to note that due to the asynchronous nature of `setState`,
you should not rely on the immediate state update when performing
calculations or accessing the updated state value immediately after calling
`setState`.
incrementCount = () => {
this.setState((prevState) => ({
count: prevState.count + 1,
}));
};
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.incrementCount}>Increment</button>
</div>
);
}
}
```
In the example above, the `Counter` component initializes the state with
a `count` property. The `incrementCount` method uses `setState` to
update the `count` state by incrementing its previous value.
**Functional Components:**
- Functional components are JavaScript functions that return JSX to
describe the component's UI.
- They are simpler and more lightweight compared to class components.
- Functional components were traditionally stateless, but with the
introduction of hooks in React 16.8, they can now have state and access
to lifecycle functionality.
- Functional components promote a more functional programming
approach and can be easier to read, test, and reason about.
**Hooks:**
- Hooks are functions provided by React that allow functional components
to have state, perform side effects, and access lifecycle functionality.
- The most commonly used hooks are `useState`, `useEffect`, and
`useContext`.
- `useState` is used to manage state within a functional component. It
returns an array with two elements: the current state value and a function
to update the state.
- `useEffect` is used to perform side effects, such as fetching data,
subscribing to events, or modifying the DOM. It replaces the functionality
of lifecycle methods in class components.
- `useContext` is used to consume context created with the
`React.createContext` API.
- Hooks are used by calling them at the top level of a functional component,
not within loops, conditions, or nested functions.
useEffect(() => {
document.title = `Count: ${count}`;
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
```
**`useState` Hook:**
- The `useState` hook is a built-in hook provided by React for managing
state within functional components.
- It allows you to add stateful behavior to your functional components
without converting them into class components.
- `useState` returns an array with two elements: the current state value
and a function to update the state.
- The syntax for using `useState` is as follows: `const [state, setState] =
useState(initialValue);`
- `state` is the current state value.
- `setState` is the function used to update the state. It accepts a new
value and triggers a re-render of the component.
- `initialValue` is the initial value of the state.
- You can call `useState` multiple times in a single component to manage
multiple state values.
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
```
The `useState` hook is a powerful tool for managing state within functional
components in React. It simplifies state management and allows you to
write more concise and readable code.
useEffect Hooks(Func onal Component)
**`useEffect` Hook:**
- The `useEffect` hook is a built-in hook provided by React for handling
side effects in functional components.
- It allows you to perform operations such as data fetching, subscriptions,
or manually changing the DOM after the component has rendered.
- `useEffect` replaces the functionality of lifecycle methods like
`componentDidMount`, `componentDidUpdate`, and
`componentWillUnmount` in class components.
- `useEffect` accepts two arguments: a function that represents the effect
and an optional array of dependencies.
- The effect function is executed after the component has rendered.
- The dependencies array specifies values that, when changed, should
trigger the effect to run again. If the dependencies array is empty, the
effect runs only once, similar to `componentDidMount`.
- The effect function can return a cleanup function, which is executed
before the component is unmounted or before the effect runs again.
- You can have multiple `useEffect` hooks in a single component to handle
different side effects.
function Example() {
const [count, setCount] = useState(0);
useEffect(() => {
document.title = `Count: ${count}`;
return () => {
document.title = 'React App';
};
}, [count]);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
}
```
**`useContext` Hook:**
- The `useContext` hook is a built-in hook provided by React for consuming
context within functional components.
- It allows you to access the value provided by a context object created
using the `React.createContext` API.
- By using `useContext`, you can retrieve the current value of the context
directly within a functional component, without the need for a context
consumer component.
- `useContext` accepts a context object as its argument and returns the
current value of that context.
- Context can be shared between components at different levels of the
component tree, providing a way to pass data without explicitly passing
props through every level.
// Create a context
const ThemeContext = React.createContext();
return (
<ThemeContext.Provider value={theme}>
<App />
</ThemeContext.Provider>
);
}
**`useRef` Hook:**
- The `useRef` hook is a built-in hook provided by React for creating
mutable references that persist across renders of a component.
- It allows you to store a value that persists between renders without
triggering a re-render when the value changes.
- Unlike state variables created with `useState`, updating the value of a
`useRef` does not cause the component to re-render.
- `useRef` can be used to access and manipulate DOM elements, store
previous values, create instance variables, and more.
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={focusInput}>Focus Input</button>
</div>
);
}
```
In the example above, the `Example` component uses the `useRef` hook
to create a reference to the input element using the `ref` attribute. The
`inputRef` variable holds the reference to the input element, which can be
accessed using the `current` property. The `focusInput` function uses
`inputRef.current.focus()` to programmatically focus the input element
when the button is clicked.
The `useRef` hook provides a way to maintain mutable values that persist
across renders without triggering re-renders. It is commonly used for
accessing DOM elements, managing focus, and storing mutable values that
don't require re-rendering.
useState vs useEffect vs useContext vs useRef
**`useState`**
- Used for managing state within a functional component.
- Returns an array with the current state value and a function to update
the state.
- Triggers a re-render when the state is updated.
- Helps in maintaining and updating dynamic values specific to the
component.
**`useEffect`**
- Used for handling side effects, such as fetching data, subscribing to
events, or modifying the DOM, within a functional component.
- Replaces the functionality of lifecycle methods (`componentDidMount`,
`componentDidUpdate`, `componentWillUnmount`) in class components.
- Executes after the component has rendered.
- Accepts a function that represents the effect and an optional array of
dependencies to control when the effect should run again.
- Can return a cleanup function to perform any necessary cleanup before
unmounting or before running the effect again.
**`useContext`**
- Used for consuming context within a functional component.
- Allows access to the value provided by a context object created using
`React.createContext`.
- Retrieves the current value of the context directly within the component.
- Eliminates the need for a context consumer component.
- Requires the context object to be created before it can be consumed.
**`useRef`**
- Used for creating mutable references that persist across renders of a
component.
- Allows storing values that do not trigger a re-render when modified.
- Useful for accessing and manipulating DOM elements, storing previous
values, creating instance variables, and more.
- Returns a mutable object with a `current` property that holds the value.
It's important to note that these hooks serve different purposes and can
be used together in a single component to address different needs. Each
hook provides a specific functionality and helps in different aspects of
developing React components.
React Router
**React Router:**
- React Router is a popular library for handling routing in React
applications.
- It allows you to create single-page applications with multiple views, each
represented by a different route.
- React Router provides declarative routing, meaning you define the routes
and their corresponding components in a declarative manner.
- It supports various types of routing, including traditional URL-based
routing and hash-based routing for older browsers.
- React Router provides a collection of components and hooks that enable
navigation and routing functionality.
**Example Usage:**
```jsx
import { BrowserRouter, Switch, Route, Link, Redirect } from 'react-router-
dom';
function App() {
return (
<BrowserRouter>
<nav>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Redirect to="/" />
</Switch>
</BrowserRouter>
);
}
```
React Router is a powerful tool for handling navigation and routing in React
applications. It simplifies the process of creating multi-page-like
experiences within a single-page application.