React Intro
React Intro
Introduction
What is React JS
• React is a JavaScript library for building user
interfaces.
• React is used to build single-page applications.
• React allows us to create reusable UI
components.
• React, sometimes referred to as a frontend
JavaScript framework, is a JavaScript library
created by Facebook.
How does React Work?
• React creates a VIRTUAL DOM in memory.
• Instead of manipulating the browser's DOM
directly, React creates a virtual DOM in
memory, where it does all the necessary
manipulating, before making the changes in the
browser DOM.
• React only changes what needs to be changed!
• React finds out what changes have been made,
and changes only what needs to be changed.
How to Create React Project
• Install Node
• install npx:
– npm install -g npx
• Install create-react-app:
– npm install -g create-react-app
• create a new react app:
• npx create-react-app my-react-app
• cd my-react-app
• npm start
• Runs the default react app at http://localhost:3000/
React JSX
• JSX stands for JavaScript XML.
• JSX allows us to write HTML in React.
• JSX converts HTML tags into react elements.
Without JSX:
const myElement = React.createElement('h1', {}, 'I do not use JSX!');
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
With JSX:
const myElement = <h1>I Love JSX!</h1>;
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(myElement);
React Components
• Components are independent and reusable
bits of code.
• They serve the same purpose as JavaScript
functions, but work in isolation and return
HTML.
• When creating a React component, the
component's name MUST start with an upper
case letter.
Create React Component
• A class component must include the extends
React.Component statement. This statement creates
an inheritance to React.Component, and gives your
component access to React.Component's functions.
• The component also requires a render() method, this
method returns HTML.
function Greet() {
return <h2>Good Morning!</h2>;
}
Rendering a Component
• Use the component name as a tag <Item /> inside
the render method to show the component HTML in
the browser.
function Car(props) {
return <h2>I am a {props.color} Car!</h2>;
}
const root = reactDOM.createRoot(document.getElementById('root'));
root.render(<Car color="red"/>);
Props in the Constructor
class Car extends React.Component {
constructor(props) {
super(props);
}
render() {
return <h2>I am a {this.props.model}!</h2>;
}
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car model="Mustang"/>);
States
• React Class components have a built-in state object.
• The state object is where you store property values
that belongs to the component.
• When the state object changes, the component re-
renders.
• The state object is initialized in the constructor
• The state object can contain as many properties (all
properties that are needed for a component)
Creation of a state
changeColor = () => {
this.setState({color: "blue"});
}
React Hooks
• In React, Hooks are reusable functions that provide access to
state in React Applications.
• Hooks were introduced in the 16.8 version of React.
• Hooks give access to states for functional components while
creating a React application.
• It allows you to use state and other React features without
writing a class.
• They provide a cleaner and more concise way to handle state
and side effects in React applications.
Types of React Hooks
• State Hooks
• Context Hooks
• Ref Hooks
• Effect Hooks
• Performance Hooks
• Resource Hooks
• Other Hooks
State Hooks
React State Hooks
• State Hooks stores and provide access to the
information. To add state in Components we use:
• useState Hook useState Hooks provides state
variable with direct update access.
• useReducer Hook useReducer Hook provides a
state variable along with the update logic in
reducer function.
• const [count, setCount] = useState(0)
Context Hooks
React Context Hooks
• Context hooks make it possible to access the
information without being passed as a prop.
• useContext Hooks shares the data as a global
data with passing down props in component
tree.
• const context = useContext(myContext);
Ref Hooks
React Ref Hooks
• Refs creates the variable containing the
information not used for rendering e.g. DOM
nodes.
• useRef Declares a reference to the DOM
elements mostly a DOM Node.
• useImperativeHandle It is an additional hook
that declares a customizable reference
• const textRef = useRef(null);
Effect Hooks
React Effect Hooks:
• Effects connect the components and make it sync with the
system. It includes changes in browser DOM, networks and other
libraries.
• useEffect useEffect Hook connects the components to external
system
• useLayoutEffect used to measure the layout, fires when the
screen rerenders.
• useInsertionEffect used to insert the CSS dynamically, fires
before the changes made to DOM.
• useEffect(()->{
// Code to be executed
}, [dependencies] )
Performance Hooks
React Performance Hooks:
• Performace hooks are a way to skip the unnecessary work and
optimise the rendering preformance.
• useMemo return a memoized value reducing unnecessary
computations.
• useCallback returns a memoized callback that changes if the
dependencies are changed.
• const memoizedValue = useMemo(functionThatReturnsValue,
arrayDependencies)
• To prioritize rendering we can use these:
• useTransition enables us to specify which state changes are critical or
urgent and which are not.
• useDefferedValue allows you to postpone the rendering of a
component until a specific condition is met.
Resource Hooks
React Resource Hooks:
• It allows component to access the resource
without being a part of their state e.g.,
accessing a styling or reading a promise.
• use: used to read the value of resources e.g.,
context and promises.
• const data = use(dataPromise);
Other Hooks
Additional React Hooks:
• These are rarely used hooks mostly used in libraries.
• useDebugValue helps developers debug custom hooks in
React Developer Tools by adding additional information
and labels to those hooks.
• useID generates unique IDs i.e, returns a string that is
stable across both the server and the client sides.
• useSyncExternalStore: helps components subscribe to
external stores.
Note: We can write custom hooks also which is out of
syllabus
React Routing
• To use routing, install react-router-dom
• npm install react-router-dom
• We wrap our content first with <BrowserRouter>.
• Then we define our <Routes>. An application can have
multiple <Routes>. Our basic example only uses one.
• <Route>s can be nested. The first <Route> has a path of / and
renders the Layout component.
• The nested <Route>s inherit and add to the parent route. So
the ’login’ path is combined with the parent and becomes ‘login’
• The Home component route does not have a path but has
an index attribute. That specifies this route as the default route
for the parent route, which is /.
• Setting the path to * will act as a catch-all for any undefined URLs.
This is great for a 404 error page.
Outlet and Link
• The component which has <Outlet> and <Link> elements is the
base for navigation.
• The <Outlet> renders the current route selected.
• <Link> is used to set the URL and keep track of browsing history.
• Anytime we link to an internal path, we will use <Link> instead
of <a href="">.
• The “navigation route" is a shared component that inserts
common content on all pages, such as a navigation menu.
Navigation Component
import { Outlet, Link } from "react-router-dom";
const Layout = () => {
return ( <><nav>
<ul>
<li> <Link to="/">Home</Link>
</li> <li> <Link to="/blogs">Blogs</Link>
</li> <li> <Link to="/contact">Contact</Link>
</li>
</ul>
</nav>
<Outlet />
</> ) };
export default Layout;
Index.js
<BrowserRouter>
<Routes>
<Route path="/" element={<Login />}>
<Route index element={<Home />} />
<Route path="profile" element={<Profile />} />
<Route path="contact" element={<ContactUs />} />
</Route>
</Routes>
</BrowserRouter>
Component Lifecycle
1. Initialization phase
This is the stage where the component is constructed with the given Props
and default state. This is done in the constructor of a Component Class.
2. Mounting Phase
Mounting is the stage of rendering the JSX returned by the render method
itself.
3. Updating
Updating is the stage when the state of a component is updated and the
application is repainted.
4. Unmounting
As the name suggests Unmounting is the final step of the component
lifecycle where the component is removed from the page.
React provides the developers with a set of predefined functions that if
present are invoked around specific events in the lifetime of the
component. Developers are supposed to override the functions with the
desired logic to execute accordingly.
Lifecycle methods
Initialization
In this phase, the developer has to define the props and initial state of the
component this is generally done in the constructor of the component. The
following code snippet describes the initialization process.
getSnapshotBeforeUpdate(prevProps, prevState)
componentDidUpdate
• Similarly this function is invoked after the component is
rerendered i.e. this function gets invoked once after the
render() function is executed after the updation of State or
Props.
Class Person {
constructor(name) {
this.name = name;
}
present() {
return ‘Hello ' + this.name;
}
}
const p1 = new Person(“jyotsna");
p1.present();
Arrow Functions
• Simplified version to normal functions or a
short hand form.
Eg:
hello = function() {
return "Hello World!";
}
React Forms
Angular Vs React
#. Angular React
1. Angular is a front-end framework. React is a JavaScript library.
2. Angular uses two-way data binding and React uses one-way data binding and
real DOM. virtual DOM.
3. Used for Develop dynamic web apps Used for Build interactive UI components
4. Language- typescript Language- javascript
5. Developed and maintained by Google Developed and maintained by Meta and
community
6. Extends the functionality of HTML, Uses XML-like syntax called JSX, slight
prefers client-side rendering preference for server-side rendering
7. Performance is low when compared with Relatively high (since virtual DOM renders
react. But generally high. updates much faster & ensures fast
runtime performance)
8. Dynamic UI binding at plain object or Direct linking of states to the UI
property level
9. Supports dependency injection, allowing Does not fully enable dependency injection
for separate lifecycles for different stores because each component has its own
global state