React
What is React?
React is an open-source JavaScript library for building user interfaces, developed and maintained by Facebook. It is a popular, component-based tool used to create dynamic and interactive web applications.Mainly for Single Page Applications.
Difference between Virtual DOM & Real DOM
Real DOM is what is rendered in the browser at any time. A copy of the same is stored in the memory known as Virtual DOM.
But why do we have a copy?
Because in react there is a concept called reconciliation, a process in which React updates the Real DOM to match the Virtual DOM. Whenever the state or props of a component change, the reconciliation occurs, and using a diffing algorithm, only minimal changes are re-rendered in the Real DOM.
//Let this be our initial stage - The same DOM exists in Real DOM and Virtual Dom for now.
<div>
<span>Hello<span1>
<h1>Value</h1>
</div>
//Now if any event changes this value inside h1, the value will be first changed in virtual DOM, and after reconciliation, only the h1 tag value will be re-rendered in the UI.
<div> //Remains same
<span>Hello<span1> //Remains same
<h1>New Value</h1>
</div> //Remains same
What is a component & props?
Components:
Components are the UI blocks made using react. Functions that return JSX are called components.
There are two types of components, class based (old way) and function way.
Props:
Short for properties props are read-only data passed from a parent component to a child component.
They cannot be changed by the child. They are controlled by the parent.
function CustomBox({props: user}){ return ( <div> user.name </div> ); } //Here user is the prop passed inside CustomBox component
What is a state?
State:
Data or value inside a component is called its state.
Changing state triggers a re-render of the component to reflect updated values.
What is JSX?
JSX is a syntax extension for JavaScript that looks like HTML But is actually Javascript + XML.
It allows us to write. HTML lookalike and JS inside react components.
What is Babel?
Babel is a JavaScript compiler that transforms JSX into browser understandable JavaScript.
It allows us to use features like JSX without worrying about browser support.
const element = <h1>Hello, World!</h1>;
//Babel will convert this JSX syntax to Js as following
const element = React.createElement('h1', null, 'Hello, World!');
Hooks in react
A hook is simply a function that lets a functional component use features like state or lifecycle methods that were previously only available in class components.
useState: Allows functional components to have state. It returns a state variable and a function to update it, and updating the state triggers a re-render of the component.
import React, { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}> Increment </button> </div> ); }useEffect: Lets us perform side effects in functional components, such as fetching data or updating the DOM. It runs after the component renders and depends on a dependency array. Dependency array makes sure the useEffect runs only after the value inside it is available or changed.
import React, { useEffect, useState } from "react"; function App() { const [message, setMessage] = useState("Waiting..."); useEffect(() => { const timer = setTimeout(() => { setMessage("Five"); }, 5000); return () => clearTimeout(timer); }, []); //Dependency array return <h1>{message}</h1>; } export default App;useRef: Allows us to create a mutable reference that persists across renders. It can be used to access DOM elements directly or store values without causing re-renders.
import React, { useRef } from "react"; function TextInput() { const inputRef = useRef(); const focusInput = () => { inputRef.current.focus(); }; return ( <div> <input ref={inputRef} placeholder="Type here" /> <button onClick={focusInput}>Input</button> </div> ); }useContext: Lets us access values from a React context without passing props through intermediate components, helping to avoid prop drilling.
import React, { createContext, useContext } from "react"; const ThemeContext = createContext("light"); function ThemedText() { const theme = useContext(ThemeContext); return <p>Current theme: {theme}</p>; } function App() { return ( <ThemeContext.Provider value="dark"> <ThemedText /> </ThemeContext.Provider> ); }useReducer: Used for managing complex state logic. It takes a reducer function and an initial state and returns the current state and a dispatch function to send actions to the reducer. Mostly used for making one state instead of multiple useState.
import React, { useReducer } from "react"; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } } function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div> <p>Count: {state.count}</p> <button onClick={() => dispatch({ type: "increment" })}>+</button> <button onClick={() => dispatch({ type: "decrement" })}>-</button> </div> ); }
Controlled and Uncontrolled Components
Controlled Components: Component or element whose state is controlled by React itself. This means that the component's state is stored in a React component's state and can only be updated by triggering a state change via setState from useState.
const [name, setName] = useState("");
<input value={name} onChange={e => setName(e.target.value)} />
Uncontrolled Components: Components where the form element's state is not directly controlled by React. Instead, the form element itself maintains its own state, and React only interacts with the element indirectly through references (refs).
const inputRef = useRef();
<input ref={inputRef} />
Prop Drilling
Prop drilling is when props are passed through many layers of components just to reach a child that needs it. It is hard to manage if the app is big.
Ways to avoid prop drilling
Use React Context or state management libraries (like Redux) to avoid passing props manually through each level.
For one level, prop drilling is fine, but for multiple level, we shoulf use state management tools.
function CustomBox({props: user}){
return ( <div> <UserBox props={user}> </div> )
}
function UserBox({props: user}){
return ( <div> <UserHeader props={user}> </div> );
}
//Here user is the prop passed at multiple levels, so we should prefer using a state management tool.
State Uplifting
State uplifting means moving state up to the nearest common parent of components that need to share it.
We also sometimes use it to maintain Single Source of Truth in react apps.