React Js Notes
React Js Notes
Facebook (Jordan Walke) introduced React in the year 2011 and made it as an open source in 2013.
2. Fast Development
5. More Expensive
2. Slow Development
3. Slower maintenance
5. Less Expensive
Features of react:
1] Declarative
5] Virtual DOM
Virtual DOM
1. Virtual DOM is a copy of real DOM, you can say a xerox copy.
2. Whatever updation we do on the virtual dom is not reflected on the real dom or the screen directly.
3. It does all the manipulation within itself and then render those changes on the real dom so in this
way we do not need to update the real dom again and again.
Diffing :
React compares the virtual copy of the real dom to an updated copy of virtual dom , compares or picks
out the changes. This process is called as diffing and the algorithm used is called as diffing algorithm.
Reconciliation:
When a component(node) changes , react decides whether it should render the changes on real dom
or not.
So if the states/props of two nodes/components are not same, then it renders the changes to Real
DOM.
In react, when the state of a component changes, the component needs to update its UI to reflect new
state.
It is dependent on :
1. Virtual DOM
2. Diffing Algorithm
Installation of vite
1]Install node JS (after installing close everything and install it only once)
2]Create a folder
3]Open with cmd(Command Prompt)
5]Ok to proceed? y?
8] Select variant:JavaScript
9] cd project-name
2. It is Declarative
Folder Structure:
node-modules: All the pre-defined codes are present in this folder(do not touch it)
src :
i. main.jsx :This will create a connection between the src and index.html
package-lock.json & package.json: These are considered as directories of the react folder.It will provide
you information about libraries present in the project.
Rules of JSX:
1. JSX must be closed, which means each and every element should be closed.
<h1>.....</h1>
Even if it is a void tag or empty tag then close the element there itself.
<input/>
2. JSX must have one parent element or else you can get one error.
<div>
<h1>JSX....</h1>
<h2>JSX....</h2>
</div>
<h1>...</h1>
4. In html we used attribute 'class' and 'for'. But in jsx we will use 'className' and 'htmlFor'.
JSX Expressions:
1. With JSX you can write expressions inside curly braces {}.
2. The expression can be a react variable, or property or any other valid javaScript expression.
COMPONENTS:
2.Webpage will be divided into multiple components(files) and then we will be joining together in the
parent component (App.jsx).
Types of Components:
2. FBC is stateless.
return (
<h1>Hello</h1>
1. It uses class.
2. CBC is statefull.
5. render() is used.
render(){
return(
**PROPS**
1. Props are nothing but properties.
2. Props are used for transfering data from parent component to child component.
4. It is an inbuilt object.
5. Props are immutable , it means once the data is passed from parent component it can't be changed.
**FRAGMENT**
1. Fragment let you group a list of children without adding extra node to the DOM.
<React.Fragment>
</React.Fragment>
<Fragment>
</Fragment>
3]
<>
</>
** key prop provides unique identity for each data(value) inside the array which you are mapping.
** PROPS DRILLING **
1.Prop drilling occurs when a parent component passes data down to its children and then those
children pass data down to their own children.
2.At the end its a long chain of component dependencies that can be difficult to manage and maintain.
3. The problem with this approach is that most of the components through which data is passed have
no actual requirement.
4. They are simply used as mediums to transfer the data to the destination component.
** {props.children} **
We can use props.children on components that represent 'generic boxes' and that do not know their
children ahead of time. It is used to display whatever you include between opening and closing tag
when you render the component.
**Default Props: The defaultProps is a react property that allows you to set default values for the props
argument.
***Proptypes****
Proptypes are a mechanism to ensure that components use the correct datatype and pass the right
type of data and the component uses the right type of props and that receiving components receive
the right type of props.
***STATES***
1. State is a javascript object used by react to represent the information about the component's current
situation.
But we can make it statefull , using an advanced hook from react library .
SYNTAX OF useState()
let [state, setState] = useState("Hello")
**Hooks**
3. Whenever we want to use hooks, we have to import it from React library, import statement is
mandatory.
PROPS:
3. Mutability : Immutable
STATES:
2. Readability : Changeable
3. Mutability : Mutable
1. INLINE CSS
It is a type of css which will apply individually inside one particular tag using "style" attribute.
The CSS properties should be written inside an expression in the form of 'object'.
2. GLOBAL CSS
It is a type of css which we will use to maintain one css file for entire react project .
We have to create a separate css file inside 'src' with an extension of '.css' and write all the styles.
3. MODULE CSS
The respective styles required for the particular component will be written in their respective css file.
Whenever we are using module css we have to create css file with an extension '.module.css'
**CONDITIONAL RENDERING**
In react, conditional rendering is the process of displaying different content based on certain conditions
or states. It allows you to create dynamic user interface.
***ContextApi ***
1. Context is a way to share data between components without having to pass props down to the
component tree.
2. useContext is a hook that allows you to consume context values in your functional components.
3. To create a context, use the createContext() method.This returns a context object that can be used to
provide and consume values.
4. To provide a value to a child component, use the Context.Provider component. This component
accepts a value prop that is passed down to child components.
5.To consume a value in a child component, use the useContext hook. This hook takes a context object
as its argument and returns the current value of the context.
***HOC(Higher Order Components)***
HOCs are the functions that accept a component as an argument and return a new component with
additional functionality.
***References***
1. Uncontrolled Form
2. Controlled Form
1]Uncontrolled Forms:
4. Suppose if we want to take any data from user, first the data will be taken by DOM directly and then
we will be taking the data from DOM.
2]Controlled Forms:
1. In React, a controlled component is a component where form elements derive their value from a
React state.
2. When a component is controlled, the value of form elements is stored in a state and any changes
made to the value are immediately reflected in the state.
3. To create a controlled component, you need to use the value prop to set the value of form elements
and the onChange event to handle changes made to the value.
4. The value prop sets the initial value of a form element, while the onChange event is triggered
whenever the value of a form element changes.
5. Inside the onChange event, you need to update the state with the new value using a state update
function.
STEPS:
1.Synthetic events in React are cross-browser wrappers around the browser's original event or native
events.
3.They create a uniform interface that React uses to ensure that events execute consistently across all
the browsers.
4.React normalizes this information to provide a consistent API for handling events regardless of the
browser.
2.Each phase has a set of lifecycle methods that are called at specific points in the component's
lifecycle.
3. These methods allow you to control component's behavior and perform specific action at different
stages of its lifecycle.
1] MOUNTING PHASE :
Mounting phase is a phase where an instance of a component is being created and inserted into the
DOM.
i. constructor(props)
iv. componentDidMount()
2] UPDATING PHASE:
Updating phase is a phase when a component is being rendered as a result of changes either to its
props or state.
i.static getDerivedStateFromProps(prop,state)
ii.shouldComponentUpdate()
iv. render()
3] UNMOUNTING PHASE :
Unmounting phase is a phase when a component is being removed from the DOM.
ERROR HANDLING :
Error handling is a phase when there is an error during rendering in a lifecycle method .
1] MOUNTING PHASE :
i. constructor(props)
* It is a special function that will get called whenever a new component is created.
* Best place to initialize state and bind the event handlers like 'this' keyword.
ii.static getDerivedStateFromProps(prop,state)
* This method gets invoked when the state of the component depends on changes in props over
time.
iii. render()
iv.componentDidMount()
* Invoked immediately after a component and all its children components have been rendered to
the DOM.
* Can be used to cause side effects. Ex Interact with the DOM or perform any ajax calls to load data.
2] UPDATING PHASE :
i. static getDerivedStateFromProps(prop,state)
iii.getSnapshotBeforeUpdate(prevProps,prevState)
* This method is called right before the changes from the virtual DOM are to be reflected in DOM.
* The returned value will be passed as the third parameter to the componentDidUpdate method.
iv. render()
v. componentDidUpdate(prevProps,prevState,snapshot)
* This method allows you to use side effects or can be used to cause side-effects.
3] UNMOUNTING PHASE :
i.componentWillUnmount() :
* For example : Cancelling any network requests, removing event handlers, cancelling any
subscription.
When there is an error either during rendering in a lifecycle method or in the constructor of any child
component this phase occurs.
i. static getDerivedStateFromError(error)
ii. componentDidCatch(error,info)
***USEEFFECT HOOK***
1. The useEffect hook is used to handle the side effects such as fetching data and updating DOM.
2. This hook runs on every render but there is also a way of using a dependency array using which you
can control the effect of rendering.
3. You can call useEffect with a callback function that contains the side-effect logic.
6. The effect will only run again if any of the values in the dependency array change.
SYNTAX OF USE-EFFECT:
useEffect(callback,dependency)
1. useEffect(()=>{
} , [] )
// Adding empty array ensures that the useEffect gets invoked only once (When component mounts)
2. useEffect(()=>{
} , [values] )
// Adding dependency values invokes or triggers useEffect whenever they are updated in the program
// You can also give multiple values for dependencies by separating with comma.
SIDE-EFFECTS:
A react side-effect occurs when we use something that is outside the scope of React.js in our own react
components E.g. Web APIs , localStorage, etc.
1. When we talk about side effects in the context of React.js , we are referring to anything that is
outside the scope of react.
3. We usually manage React side-effects inside the useEffect hook (part of the React Hooks).
***HTTP METHODS***
HTTP methods are a set of request methods to indicate the desired action to be performed for a
given resource.
1. GET : The GET method is used to simply retrieve data from the server .
2. POST : The POST method sends data to the server for processing.
3. PUT : The PUT method is used to completely replace a resource identified by a given url.
***AXIOS***
Axios is a promise-based HTTP library that lets developers make requests to either their own server
or a third-party server to fetch data.
It offers different ways of making requests such as GET, POST , PUT/PATCH and DELETE.
**MEMOIZATION**
1. In Reatjs, performance optimization plays an important role in ensuring the smooth and efficient
rendering of components. One powerful technique for optimizing performance is Memoization.
2. Memoization is an optimization technique that allows an increase in the performance of a
program by storing the results of the function when the same inputs are given.
**PURE COMPONENTS**
A react component is considered as a pure component if it renders the same output for the same
state and props.
Its return value is always the same for the same input values.
**React.memo()**
2. The React.memo() wraps a component and checks for prop changes before re-rendering it.
3. If the props have not changed since the last render, React.memo() skips the re-rendering process
and returns the previously rendered results, which is stored in cache.
***useCallback Hook***
1. useCallback is a hook provided by React that memoizes a function so that it can be reused across
re-renders of a component without causing unnecessary re-renders.
3. The useCallback hook takes two arguments: the function to memoize and an array of
dependencies that the function depends on.
4. If any of these dependencies change , the function is re-created. If none of the dependencies
change, the memoized function is returned.
5. Memoizing functions with useCallback can help improve performance in certain scenarios, such as
when a component has a large number of child components that use memoization and receive
function as prop.
6. It is important to be careful when using useCallback and make sure that dependencies array is set
correctly. If the dependencies array is not set correctly , it can cause bugs and unexpected behaviour.
7. useCallback can also be used in conjuction with the useMemo hook to further optimize
performance by memoizing expensive computations that are used as props to child components.
***useMemo Hook***
3. This function is only executed when its dependencies change. If the dependencies don't change ,
the memoized value returned by the function is reused.
4. The second argument to useMemo is an array of dependencies. If these dependencies change, the
function will be re-executed to produce a new memoized value.
What is Router?
A router in ReactJs is a library that allows you to navigate between different pages or views within a
single page application. It manages the UrLs of your application and maps them to appropriate
components to render.
A router is needed to provide a seamless user experience when navigating through different parts of
SPA.
To use a router in ReactJs, you need to install a router library such as react-router-dom using npm.
Once installed , you can import necessary components from the library , such as BrowserRouter,
Routes, Route, Link and use them in your React components to define the routes and navigation
behaviour of your application.
** BrowserRouter**
It is a component that should wrap your entire application and provide the history and location
objects to your components. The history object keeps track of the browser's history and the location
object contains information about the current URL.
**Routes**
It is a component that wraps multiple Route components and renders Route that matches the
current URL.
**Route**
It is a component that defines a route in your application . You can specify the path for the route and
the component that should be rendered when the route is matched.
**Link**
Link is a component that provides declarative, accessible navigation around your application. It is
used to create links to different routes and implement navigation around the application. It works
like an HTML anchor tag.
***useNavigate()***
1. The useNavigate() hook is a built-in hook provided by React Router that allows you to navigate
programmatically between different pages or components.
2. It returns a navigate function that can be called with the URL or a location to navigate to a
different page or component.
3. To use this hook, you must import it from the react-router-dom library.
4. You can call the useNavigate() hook inside a functional component to access the navigate function.
5. The useNavigate can be used for navigating in response to user actions, such as button clicks or
form submissions.
6.It is important to note that useNavigate should only be used inside a component that is rendered
by routing , otherwise it will not work.
***useParams()***
1.The useParams hook is a hook that allows you to access parameters from the current url.
2.It returns an object containing key-value pairs of the parameters defined in the URL.
3. To use this hook, you must import it from the react-router-dom library.
4. You can call the useParams() hook inside a functional component to access the parameter values.
5.The parameter values can be accessed using the names defined in the url .
6. For ex. If you have a parameter named 'id' in your url , you can access it using
Installation: