React is used to build single - page applications.
React allows us to create reusable UI components.
popular for building dynamic interactive and user friendly web interfaces.
**
SETUP
**
- Install Node.js in your computer.
- now run cmd in terminal:- npm create vite@latest
- tell the project name- ex:- react
- select framework - React.
- select a variant in you'll like to code- javascript
- Use rolldown-vite (Experimental)?: - No.
- Install with npm and start now? - yes
React will run on port 5173
we can run file again with cmd:
(npm run dev)
JSX
It is a syntax extension of javascript that helps you to write HTML code in your JAVASCRIPT files.
JSX is not understood by browser directly - it is compiled into javascript using babel(a JS compiler which converts the modern JS into plain JS)
BASICS OF REACT
PROPS AND DATA FLOW
- props are a way to pass data from parent to child.
- props are passed from parent to child in one way street
- In jsx props are used in HTML, values are not string and must be enclosed in curly braces.
//App.jsx behaving like parent of file child .jsx
import React from 'react'
import Child from './Child';//This line exports the component, so other files (like App.jsx) can import and use it:
const App = () => {
let username="priya";
return (
<div>
<h1>parent component</h1>
<Child name={username} age={19} />
</div>
)
}
export default App;
import React from 'react'
const Child = (props) => {
return (
<div>
<h1> child component</h1>
<p> name:{props.name} </p>
<p> age:{props.age} </p>
</div>
)
}
export default Child;
- Here, Data goes from parent to child using props.
- The child component can display this data but cannot modify it (props are read-only).
FUNCTION() CALLING
when data is sent from a child to a parent in react the technique used is called function calling
step.1 - Parent Component
Define a function that will handle the data received from the child, such as updating its state
Pass the function as a prop to the child component.
Step.2 - Child component
Receive the function as a prop from the parent.
when an event occurs (e.g., a button click, form submission), call
the received function (prop).Pass the data you want to send to the parent as an argument to this
function call.
An example of sending data from a child to parent by calling a function
1.getNameFromChild is defined inside the parent, takes childName as parameter then updates the parent's state using setName(childName).
2.Parent send the function (getNameFromChild) to the Child as a prop called sendName.
3.The child receives the sendName prop from the parent, child has its own local varible name='Priya'.
4.sendName actually refers to the parent’s getNameFromChild function.
LOCAL VARIABLES
local varibles are declared within the component function.
changes to them do not trigger re-render.
3.They are re-initialized on every re-render of the component+
- Here clicking on button will not update the UI, because count is a local variable.
- Every time the component re-renders ,React runs the component function again so the count is set back to 0.
- Even if you increment it in the Handleclick , the next render resets it so the UI never changes, because UI depends of Render.
STATE VARIABLES
-
It is managed by useState hook(it return an array containing two elements)-
1. current value.
2. setter function.**const [count, setCount] = useState(0);**
Immutable, we cannot directly modify the state varible instead we need to create a new version of the value and update it.
When we call the setter(setCount) react re-renders the component with the updated value.
It is state persistent as - counter keeps its value after re-render.
-here, component mounts count =0(initial value).
-user clicks button setCount(count+1) runs.
-React updates count and re-renders the component.
-UI shows the new value.
CONDITIONAL RENDERING
-Our components will often need to display different things depending on different conditions.
-Render different components depending on user login status, etc.
-conditionally render JSX using JavaScript syntax like if statements, &&, and ? : operators.
THE MAP() FUNCTION
- React component's return statement, use curly braces {} to embed JavaScript expressions.
- Provide a unique key prop:helps React efficiently identify and manage individual items
USEREF() HOOK
- If we count how many times our application renders using the useState Hook, we would be caught in an infinite loop since this Hook itself causes a re-render.
- useRef() only returns one item, it return an object called current. 3.It is a hook to access and store the mutable value that does not trigger re-render when it changes.
- useRef() for Dom elements
- useRef() for persisting values between renders.
import React, { useRef, useState } from "react";
const UseRefRender = () => {
const [count, setCount] = useState(0);
const renderCount = useRef(0); // initial value
// This will run every render — no useEffect needed
renderCount.current = renderCount.current + 1;
return (
<div>
<h2>Count: {count}</h2>
<h3>Rendered: {renderCount.current} times</h3>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
};
export default UseRefRender;
**OUTPUT**
Count: 0
Rendered: 1 times
-- as before React renders the component, our code explicitly increments the ref by +1.
--That line always runs during rendering, even the very first time.
that why it is rendered
--Count: 0” → from useState(0)
“Rendered: 1 times” → because your ref started at 0 and you incremented it once during the very first render.
CONTEXT API
- an alternative to passing props 1.The context API in react is a state management tool that allows you to share data across multiple components without having to pass props manually at every level of the component tree. 2.Context API is used to pass global variables in anywhere in the code without prop drilling 3.Context API solves the problem of prop drilling in React.Prop Drilling occurs when data is to be passed b/w multiple layers before sending it to the required component 4.It helps when there is need of sharing state between a lot of nested components.
WORKING OF CONTEXT API
step-1 : Create the context-using React.createContext()
import React, { createContext, useContext, useState } from "react";
// 1️⃣ Create Context
const UserContext = createContext();
step-2:Provide Context -using a component
// 2️⃣ Provide the context value
<UserContext.Provider value={user}>
<Child />
</UserContext.Provider>
step-3:Consume Context- using useContext() hook
// 3️⃣ Consume context value
const user = useContext(UserContext);
return <h1>Hello, {user}!</h1>;
HERE, is whole code how you can use it
REACT LIFECYCLE
- It describes the various stages a component goes through from its creation to its removal
Phases of lifecycle in React Components
1.MOUNTING
- The process of creating and inserting a component into the DOM for the first time, During mounting, React initializes the component ,sets up its internal state and inserts it into the DOM
ORDER OF METHODS
- Constructor- called when component is initiated, helps to bind method
- getderivedStateFromProps() - update state before rendering.
- render() - return JSX.
- componentDidMount()- runs after the component is rendered to the DOM.
2.UPDATING
- A component is updated when there is a change in the components state or props
ORDER OF METHODS
1.getDerivedStateFromProps()- first method which is called when a component gets updated
2.shouldComponentUpdate()- method you can return a Boolean value that specifies whether React should continue with the rendering or not.
3.render()- method is of course called when a component gets updated, it has to re-render the HTML to the DOM, with the new changes.
4.getSnapshotBeforeUpdate()- we have access to the props and state before the update, meaning that even after the update, you can check what the values were before the update.
5.componentDidUpdate()- method is called after the component is updated in the DOM
3.UNMOUNTING
- When the component is removed from the DOM.
order of methods
1.componentWillUnmount()- method is called when the component is about to be removed from the DOM
USEEFFECT() HOOK
-allows us to perform side effects(refers to any operations within the component that interact with world wide component fetching data, directly updating the DOM, and timers.) in our components
--IF WE don't pass array in use effect it will run after every function for avoiding this continuous running of use effect we can also pass empty array.
--we can make useEffect run only once (like componentDidMount) by passing an empty dependency array []:
--syntax of useEffect
import React, { useEffect } from 'react';
function MyComponent() {
useEffect(() => {
// Side effect code goes here
// Optional: Return a cleanup function
return () => {
// Cleanup logic (e.g., unsubscribe from a subscription, clear a timer)
};
}, [dependency1, dependency2]); // Optional: Dependency array
}
useEffect(() => {
console.log("Count changed:", count);
}, [count]); // runs only when 'count' changes
--Good for reacting to state changes (e.g., refetching data when filters change)
USEMEMO() HOOK
useMemo Hook returns a memoized value.
It only runs when one of its dependencies update.
It prevents unnecessary re-execution of program.
It re-renders only when props change.
Components nested inside memoized components (like Gc) will re-render whenever the parent memoized component re-renders.
It takes two argument.
A function that returns the value you want to memoize.
A dependency array.
const memoizedValue = useMemo(() => {
// Perform an expensive computation here
return computedResult;
}, [dependency1, dependency2, ...]);
An example of useMemo();
import React, { memo, useState } from "react";
const MemoChild1 = memo(function Child1({ dukaan }) {
console.log("Running Child1");
return <div>I am child1</div>;
});
const MemoChild2 = memo(function Child2({ study }) {
console.log("Running Child2");
return (
<div>
I am Child2
<Gc />
</div>
);
});
function Gc() {
console.log("Running GC");
return <div>I am GC</div>;
}
function Parent() {
const [dukan, setDukan] = useState(1);
const [study, setStudy] = useState(1);
console.log("Running Parent");
return (
<div>
<button onClick={() => setDukan(dukan + 1)}>Updatee Dukan</button>
<button onClick={() => setStudy(study + 1)}>Updatee Study</button>
<MemoChild1 dukaan={dukan} />
<MemoChild2 study={study} />
</div>
);
}
const App = () => {
return (
<div>
<Parent />
</div>
);
};
export default App;
- here is memoized child1 functions, showing that it will only re-render when its props (dukaan) changes.
2.And child2 is also memoized , only re-renders when the study changes but it renders the another component GC.
3.GC is not memoized so everytime Child2 re-renders , this component runs again
Render behaviour in action:-
1.Click “Update Dukan”
dukan state changes → Parent re-renders.
Child1 re-renders (since dukaan prop changed).
Child2 does not re-render (since study prop didn’t change).
Gc does not run again (because Child2 didn’t re-render).
2.Click “Update Study”
study state changes → Parent re-renders.
Child2 re-renders (since study prop changed).
Child1 does not re-render (since dukaan prop didn’t change).
Gc runs again (since Child2 re-rendered).
Top comments (0)