React PPT
React PPT
• Store Update: The store notifies subscribers (usually components) that the
state has changed.
• Re-rendering: Components read the updated state from the store and re-
render, reflecting the changes in the UI.
Principles of Redux
1.) Single Source of Truth
The state of your whole application is stored in an object tree
within a single-store
• The React Context API is a built-in feature in React that allows you to share data across
the component tree without explicitly passing props down through every level. This
makes it easier to share data between components.
• It's a way to create "global variables" for your application, making it useful for managing
state across deeply nested components without the need for prop drilling.
React Context API
Basically, Context API consists of two main components: the context provider
and the context consumer. The provider is responsible for creating and
managing the context, which holds the data to be shared between
components. On the other hand, the consumer is used to access the context
and its data from within a component.
Creating a Context:
You use the createContext() function to create a context object. This object has two parts:
a Provider and a Consumer.
Provider: This component allows you to provide a value to any of its descendant components.
Consumer: This component is how descendant components can access the provided value.
React Components: function and class
components
In React, components are the building blocks of a user interface.
They are reusable, self-contained pieces of code that represent a
part of the UI. React allows you to break down your UI into
smaller components, which makes it easier to manage and
maintain your codebase.
They can accept inputs called props (short for properties) and
return React elements describing what should appear on the
screen.
There are two primary ways to create components: function and
class components. Each has its own syntax and use cases,
although with the introduction of React Hooks, the gap between
them has narrowed significantly.
Function Components: These are simple JavaScript functions
that take props as input and return JSX elements. They are often
used for presentational or stateless components.
React Components: function and class
components
Class Components: These are ES6 classes that extend
from React.Component or React.PureComponent. [ES6 classes in
JavaScript provide a more organized and familiar way to create objects and handle inheritance,
They have
offering a structured approach to object-oriented programming.]
The constructor() method is called when the component is first created. You use it to initialize the component's
state and bind methods to the component's instance.
The render() method is responsible for generating the component's virtual DOM representation based on its
current props and state. It is called every time the component needs to be re-rendered, either because its props
or state have changed, or because a parent component has been re-rendered.
The componentDidMount() method is called once the component has been mounted into the DOM.
Component Life cycle: Updating Phase
• This phase occurs when a component's props or state changes, and the
component needs to be updated in the DOM.
The shouldComponentUpdate() lifecycle method
The shouldComponentUpdate() method is called before a component is updated. It takes two
arguments: nextProps and nextState. This method returns a boolean value that determines
whether the component should update or not. If this method returns true, the component
will update, and if it returns false, the component will not update.
The componentWillUpdate() lifecycle method
componentWillUpdate() is a lifecycle method in React that gets called just before a
component's update cycle starts.
The componentDidUpdate lifecycle method
The componentDidUpdate() method is a lifecycle method in React that is called after a
component has been updated and re-rendered. It is useful for performing side effects or
additional operations when the component's props or state have changed.
The getSnapshotBeforeUpdate lifecycle method
The getSnapshotBeforeUpdate() method is called just before the component's UI is updated
Component Life cycle: Unmounting
Component Unmounting Phase
The unmounting phase refers to the lifecycle stage when a component is being removed from
the DOM (Document Object Model) and is no longer rendered or accessible.
During this phase, React performs a series of cleanup operations to ensure that the
component and its associated resources are properly disposed of.
The unmounting phase is the last stage in the lifecycle of a React component and occurs
when the component is being removed from the DOM tree.
The componentWillUnmount() lifecycle method
componentWillUnmount(): This method is called just before the component is removed from
the DOM. It allows you to perform any necessary cleanup, such as canceling timers, removing
event listeners, or clearing any data structures that were set up during the mounting phase.
After componentWillUnmount() is called, the component is removed from the DOM and all of
its state and props are destroyed.
Controlled vs Uncontrolled Components
Controlled components in React are the components whose state
and behaviors are managed by React components using states
while the uncontrolled components manage their own state and
control their behaviors with the help of DOM.
Controlled Components
• In React, Controlled Components are those in which form’s data
is handled by the component’s state. It takes its current value
through props and makes changes through callbacks like onClick,
onChange, etc. A parent component manages its own state and
passes the new values as props to the controlled component.
Uncontrolled Components
• Uncontrolled Components are the components that do not rely on
the React state and are handled by the
DOM (Document Object Model).
Building Forms with Controlled Components in React
Generally, when we use forms in a web app, the form state lives inside the
DOM. The whole point of React is to manage the state inside applications
more effectively. We can solve this problem with controlled components.
Controlled Components refer to components that render a form, but the
“source of truth” for that form state lives inside of the component state
rather than inside of the DOM. The reason they are called controlled
components is that React is controlling the state of the form.
const MyForm = () => {
const [name, setName] = useState("");
const handleChange = (e) => {
setName(e.target.value);
};
return (
<form>
<input id="name" value="{name}" onChange={handleChange} />
</form>
);
};
Reusable React Components
They are pieces of code that can be shared and reused across
different files in your application. It is a modular piece of UI that takes
data from props to build complex and interactive user interfaces.
When creating reusable React components, it's important to keep in
mind two key factors
Avoid side Effects:
• JavaScript was earlier mainly used for frontend development. With Node JS,
JavaScript became a backend language as well.
• The V8 engine compiles JavaScript to machine code, making NodeJS fast and
efficient.
• Simplest JS Code: console.log("Hello, World!");
Save this code in file hello.js. With the command node hello.js,
NodeJs executes JavaScript in a server environment or via the command line.
21
Node.js REPL (Read-Eval-Print Loop)
• Is an interactive shell that processes Node.js expressions.
• It reads the code that is input, evaluates it, prints the result, and then
loops to read more code.
• Read : It reads the inputs from users and parses it into JavaScript data
structure. It is then stored to memory.
Eval : The parsed JavaScript data structure is evaluated for the results.
Print : The result is printed after the evaluation.
Loop : Loops the input command. To come out of NODE REPL,
press ctrl+c twice
• This environment is very useful for experimenting with JavaScript and
Node.js code, debugging, and performing quick calculations.
22
Using the Node.js REPL:
23
• Executing Code:
• Type JavaScript expressions and press Enter to see the results.
• Multiline Expressions:
• Use Shift + Enter to write multiline code
• > function add(a, b) { ... return a + b; ... } undefined > add(5, 10) 15
• Command History:
• Use the up and down arrow keys to navigate through the history of
commands you have entered.
24
• REPL Commands:
• Special commands that start with a dot:
• .help - Displays help for special commands.
• .editor - Enters editor mode for writing multiline code.
• .exit - Exits the REPL.
• .save [filename] - Saves the current REPL session to a file.
• .load [filename] - Loads a file into the current REPL session.
• Using the Editor Mode:
• Type .editor and press Enter
• > .editor
• You will enter a new mode where you can write multiline code. Press Ctrl + D
to execute the code and return to the REPL prompt.
25
NPM (Node Package Manager)
• NPM is a package manager for Node.js packages.
• www.npmjs.com hosts thousands of free packages to download and use.
• The NPM program is installed on your computer when you install Node.js
It is the default package manager for Node.js,
It comes bundled with the Node.js installation.
• Downloading any package in NPM is very easy.
• Open the command line interface and tell NPM to download the package you
want.
• E.g. to download a package called "upper-case“, write
npm install upper-case
• NPM creates a folder named "node_modules", where the package will be placed.
All packages you install in the future will be placed in this folder.
• Once the package is installed, it is ready to use. var uc = require('upper-case');
26
Installing NPM
NPM is installed automatically with Node.js. To check if NPM is installed, and
to verify the installed version, write:
npm -v
• use the -y flag to automatically set up with default values.It answers yes to any
prompys that npm might print on command line.
npm init -y
27
To install a package globally (available across all projects), use the -g flag:
npm install -g <package-name>
• Install Dependencies:
• Install a package, for example, Express, which is a web framework for Node.js:
npm install express
• Uninstalling Packages:
• Updating Packages:
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
App.js
• In App.js, we have only one component. One component is written in one file. There are two
import statements that import image and css applicable on the component
import logo from './logo.svg';
import './App.css’;
These two files are also in the src folder. logo.svg contains the logo/image that is displayed when
we execute the project and app.css contains the css specific to component while index.css has
universal css
*Try changing background color or color in app.css and then refresh the browser to see the changes.
• Now, Component can be developed in two ways: using function and using class.
• In app.js, component is developed using function. The function App() is written and this is actually
the component.
• jsx is written inside this function. Html like code is written in js file which is not allowed. So, this
html like code is called jsx.
• The component has the code corresponding to the output i.e. an image <img>, a paragraph <p>
and a link <a>.
• App.js is exported in the last line and imported in index.js. There it is rendered at div with id ‘root’
Summary of Flow
• Component is developed in App.js and its related css is written in app.css. We
import logo and app.css in app.js. We don’t have to link css with app.js. This task
is performed by React.
• A function is written in app.js with the same name as file to create component.
The html like code written inside this function is called jsx.
• This function is then exported.
• Index.js is the main file that first gets executed. It imports react and react-dom.
React-dom has a method render which renders the App component at div with
id=‘root’, which is available in index.html. This can be checked by right click and
inspecting the output in browser. We find header, image, p tag, a tag all inside
root.
• All the files mentioned above have been provided by default by ‘fb’.
• App.js->index.js->index.html->browser
Writing own code
• We write below function in app.js to create component.
import ‘./app.css’;
function App() {
return (
<div className=“app-first">
<h1>First Component</h1>
<p> I like to explore</p>
</div>
);
}
export default App;
• We write classname and not class in jsx. This classname is used in app.css for styling
• To write multiple statements in return, we place them inside a div which acts as a
wrapper. Now, h1 and p act as children of div. This is done because we can return only
one statement in return.
• We export this app and write default with app so that we may change its name when
we import it
Writing own code
• we keep the css of each component separate. In app.css, we write the code below
and import app.css in app.js:
.app-first{
background-color:green;
}
• Now we create index.js and import app.js in it. We write below code:
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />,document.getElementById('root’));
This code will give the output:
First Component
I like to explore
• our first component is created and passed to index.js which sends it to div with
id=root which is available on index.html.
Writing own code
• App.js will be used as a master/parent component. It will act as path for sending
other components. To avoid mess in src of keeping files of components and their css,
A separate folder ‘components’ will be created inside src folder for all the remaining
components which will be further sent to app.js.
• A Separate file is created for each component.
• Let we create a file FirstSubComp.js. Now, the name of function inside this file would
also be same. This function is called component (like app() function in app.js is a
component). We write below code:
function FirstSubComp() {
return (
<p>This is a sub Component</p>
);
}
export default FirstSubComp;
• Now this new subcomponent is imported in parent component i.e. App.js with below
code:
Import FirstSubComp from ./components/FirstSubComp
Writing own code
Now code of App.js is
import FirstSubComp from ./components/FirstSubComp
function App() {
return (
< FirstSubComp />
);
}
Export default App;
• in return Html tag starts with small letters e.g. h1 while components start with capital
• To write css for the subcomponent, we create css file with same name i.e.
FirstSubComp.css. To add css, we make changes in FirstSubComp
function by adding a class and using same class in css file too.
import ‘./ FirstSubComp.css’ //necessary to mention extension css
function FirstSubComp() {
return (
<p className=“abc”>This is a sub Component</p>
);
}
Overall Flow
SubcomponentApp.js Index.jsindex.html Browser
Props
How to pass data in components is called props
First, in app.js, create variables
import FirstSubComp from ./components/FirstSubComp
function App() {
let ourTitle=“Hello World”;
let ourMoney=10;
return (
<FirstSubComp>
title={ourTitle} //We can even directly write a
string
money={ourMoney} e.g. “Hello World” here
</FirstSubComp>
);
}
Export default App;
We pass the data from app.js
We receive the data passed from App.js through parameters called props. Props is
actually an object and all the data becomes its property. It is not necessary to use
props as the name of object. Some other name may be used too
Code without props
function FirstSubComp() {
return (<div>
<p>This is a sub Component</p>
<h1> 5000 </h1>
</div>
);
}
Code without props
function FirstSubComp(props) {
return (<div>
<p>{props.title}</p>
<h1> {props.amount}</h1>
</div>
);
}
Multiple component
How to attach one component inside another component
To attach a component inside another, simply write:
function FirstSubComp(props) {
return (
<div>
< SecondSubComp />
<div className=“FirstSubComp.css”>
<p>{props.title}</p>
<h1> {props.amount}</h1>
</div>
</div>
);
}
States in React
React components has a built-in state object. To use state, we have to import a function useState() from React library. This
function is also called Reacthook. Hook starts from use keyword.
This function returns an array with two values: a variable and a function. So, we do array destructuring. Variable is assigned the
name title and function is assigned the name titleChange.
The state object is where you store property values that belong to the component.
•
React Myths