HTML Basic Examples


What is Reactjs??

React is a JavaScript library that makes building user interfaces easy. It was developed by Facebook.

Does React use HTML?

No, It uses JSX, which is similar to HTML.

When was React first released?

React was first released on March 2013.

Give me two most significant drawbacks of React?

Integrating React with the MVC framework like Rails requires complex configuration.

React require the users to have knowledge about the integration of user interface into MVC framework.

State the difference between Real DOM and Virtual DOM?

Real DOMVirtual DOM
It is updated slowlyIt updates faster
It allows a direct update from HTMLIt cannot be used to update HTML directly.
It wastes too much memoryMemory consumption is less

What is Flux Concept In React?

Facebook widely uses flux architecture concept for developing client-side web applications. It is not a framework or a library. It is simply a new kind of architecture that complements React and the concept of Unidirectional Data Flow.

Define the term Redux in React?

Redux is a library used for front end development. It is a state container for JavaScript applications which should be used for the applications state management. You can test and run an application developed with Redux in different environments

What is the 'Store' feature in Redux?

Redux has a feature called 'Store' which allows you to save the application's entire State at one place. Therefore all it's component's State are stored in the Store so that you will get regular updates directly from the Store. The single state tree helps you to keep track of changes over time and debug or inspect the application.

What is an action in Redux?

It is a function which returns an action object. The action-type and the action data are always stored in the action object. Actions can send data between the Store and the software application. All information retrieved by the Store is produced by the actions.

Name the important features of React?

Here, are important features of React:

Allows you to use 3rd party libraries

Time-Saving

Faster Development

Simplicity and Composable

Fully supported by

Facebook.

Code Stability with One-directional data binding React Components

What is meant by callback function? What is its purpose?

A callback function should be called when setState has finished, and the component is retendered. As the setState is asynchronous, which is why it takes in a second callback function.

Explain the term high order component?

A higher-order component also shortly known as HOC is an advanced technique for reusing component logic. It is not a part of the React API, but they are a pattern which emerges from React’s compositional nature.

What are Props in react js?

Props mean properties, which is a way of passing data from parent to child. We can say that props are just a communication channel between components. It is always moving from parent to child component.

Name two types of React component?

Function componentClass component

Explain synthetic event in React js?

Synthetic event is a kind of object which acts as a cross-browser wrapper around the browser’s native event. It also helps us to combine the behaviors of various browser into signal API.

What is React State?

It is an object which decides how a specific component renders and how it behaves. The state stores the information which can be changed over the lifetime of a React component.

Explain the use of the arrow function in React?

The arrow function helps you to predict the behavior of bugs when passed as a callback. Therefore, it prevents bug caused by this all together.

State the main difference between Pros and State?

StatePros
State is mutablePros are immutable
State information that will change, we need to utilize StateProps are set by the parent and which are settled all through the lifetime of a part.

You can’t update props in react js because props are read-only.

Explain pure components in React js?

Pure components are the fastest components which can replace any component with only a render(). It helps you to enhance the simplicity of the code and performance of the application.

Explain strict mode?

StrictMode allows you to run checks and warnings for react components. It runs only on development build. It helps you to highlight the issues without rendering any visible UI.

What is the use of Webpack?

Webpack in basically is a module builder. It is mainly runs during the development process.

What is Babel in React js?

Babel, is a JavaScript compiler that converts latest JavaScript like ES6, ES7 into plain old ES5 JavaScript that most browsers understand.

How can a browser read JSX file?

If you want the browser to read JSX, then that JSX file should be replaced using a JSX transformer like Babel and then send back to the browser.

What are the major issues of using MVC architecture in React?

DOM handling is quite expensive

Most of the time applications were slow and inefficient

Because of circular functions, a complex model has been created around models and ideas

Explain the term synthetic events?

It is actually a cross-browser wrapper around the browser’s native event. These events have interface stopPropagation() and preventDefault().

Explain the term reconciliation?

When a component's state or props change then rest will compare the rendered element with previously rendered DOM and will update the actual DOM if it is needed. This process is known as reconciliation.

Explain Hooks?

useState: . This React hook allows components to manage local state without class components.

Store simple values like numbers, strings, objects, or arrays.

import React, { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0); // Initialize state
return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default Counter; <xmp> </code> </div> </div> <p>Avoid directly mutating the state. Instead, always update it using ‘setState'</p> <p class="text-lg text-gray-700"><strong>useEffect: </strong>. useEffect is used for tasks like data fetching, setting up subscriptions, and performing initial actions. It behaves similarly to componentDidMount in class components </p> <p>Runs after rendering. You can control when it executes by passing dependencies. It functions similarly to shouldComponentUpdate or componentDidUpdate</p> <div class="example"> <div class="code"> <code> import React, { useState, useEffect } from 'react';<br> function ExampleComponent() {<br> const [count, setCount] = useState(0);<br> // Run side effect after render<br> useEffect(() => {<br> document.title = `Count: ${count}`; // Update document title<br> // Cleanup (optional)<br> return () => {<br> document.title = 'React App';<br> };<br> }, [count]); // Dependency array: run when count changes<br> <xmp> return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default ExampleComponent;

useRef: . It is used to create mutable references to DOM elements and any values that you want to persist across renders without causing re-renders.

Autofocus an input field.

Useful for handling animations, measuring elements, and persisting values without re-renders.

import React, { useRef } from 'react';
function TextInput() {
const inputRef = useRef(null);
const focusInput = () => {
inputRef.current.focus(); // Access DOM element
}; return ( <div> <input ref={inputRef} type="text" placeholder="Type here" /> <button onClick={focusInput}>Focus Input</button> </div> ); } export default TextInput; <xmp> </code> </div> </div> <p class="text-lg text-gray-700"><strong>useMemo: </strong>. Returns a cached value and prevents expensive calculations from running on every render. </p> <p>Use it only when necessary—overusing can degrade performance.</p> <div class="example"> <div class="code"> <code> import React, { useState, useMemo } from 'react';<br> function ExpensiveComponent() {<br> const [count, setCount] = useState(0);<br> // Memoize expensive computation<br> const expensiveValue = useMemo(() => {<br> return Array(1000000).fill().reduce((sum, _, i) => sum + i, count);<br> }, [count]); // Recompute only if count changes<br> <xmp> return ( <div> <p>Count: {count}</p> <p>Expensive Value: {expensiveValue}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); } export default ExpensiveComponent;

useCallback: . Memoizes a function, ensuring that the function reference remains stable across re-renders unless its dependencies change. This is especially useful when passing functions down to child components, as it prevents unnecessary re-renders.

Use it when passing functions to child components to prevent unnecessary renders.

import React, { useState, useCallback } from 'react';
function Counter() {
const [count, setCount] = useState(0);
// Memoize the increment function
const increment = useCallback(() => {
setCount(prevCount => prevCount + 1);
}, []); // Empty dependency array: function is memoized and won't change
return ( <div> <p>Count: {count}</p> <button onClick={increment}>Increment</button> </div> ); } export default Counter; </code>xmp> </code> </div> </div> <p class="text-lg text-gray-700"><strong>useReducer: </strong>. Useful when state management is more complex than a simple state change (like useState). </p> <p>Like useState, useReducer is local to the component, but it gives you more flexibility and control over how the state is updated.</p> <p>Works great for managing form states and complex UI state logic.</p> <div class="example"> <div class="code"> <code> import React, { useReducer } from 'react';<br> const initialState = { count: 0 };<br> const reducer = (state, action) => {<br> switch (action.type) {<br> case 'increment': return { count: state.count + 1 };<br> case 'decrement': return { count: state.count - 1 };<br> default: return state;<br> }<br> };<br> function Counter() {<br> const [state, dispatch] = useReducer(reducer, initialState);<br> <xmp> return ( <div> <p>{state.count}</p> <button onClick={() => dispatch({ type: 'increment' })}>+</button> <button onClick={() => dispatch({ type: 'decrement' })}>-</button> </div> ); } export default Counter;

useLayoutEffect: . Like useEffect, but fires synchronously after the DOM has been updated but before the browser has painted the changes.

useful for animations and layout measurements.

Avoid blocking the UI—use it only for UI calculations and measurements.

import React, { useLayoutEffect, useRef } from 'react';
function ExampleComponent() {
const divRef = useRef(null);
useLayoutEffect(() => {
// Adjust the div's width immediately after DOM update
divRef.current.style.width = '200px';
}, []);
return <div ref={divRef} style="">Resize me</div>;</code>xmp> }<br> export default ExampleComponent;<br> </code> </div> </div> <p class="text-lg text-gray-700"><strong>useId: </strong>. useId is a Hook that generates unique, stable IDs that are consistent across re-renders. </p> <p>Useful in scenarios involving form elements, dynamic content, or any situation requiring guaranteed unique identifiers across re-renders.</p> <div class="example"> <div class="code"> <code> import React, { useId } from 'react';<br> function ExampleComponent() {<br> const id = useId();<br> <xmp> return ( <div> <label htmlFor={id}>Username</label> <input id={id} type="text" placeholder="Enter username" /> </div> ); }
export default ExampleComponent;

useDeferredValue: . Defers updates to prevent UI lag during heavy computations.

It’s similar to a debounce function but without a timeout. It defers the update until React is done processing other tasks.

Use it for search bars, filtering, or UI-heavy components.

import React, { useState, useDeferredValue } from 'react'; function ExampleComponent() { const [input, setInput] = useState(''); const deferredInput = useDeferredValue(input); const handleChange = (e) => { setInput(e.target.value); }; return ( <div> <input type="text" value={input} onChange={handleChange} placeholder="Type something..." /> <p>Deferred value: {deferredInput}</p> </div> ); } export default ExampleComponent;

useTransition: . Allows non-blocking UI updates for better user experience. It’s pertcularly useful when you need to update multiple states without rendering immidietly

import React, { useState, useTransition } from 'react';
function ExampleComponent() {
const [input, setInput] = useState('');
const [items, setItems] = useState([]);
const [isPending, startTransition] = useTransition();
const handleChange = (e) => {
setInput(e.target.value);
// Mark this state update as a transition (non-urgent)
startTransition(() => {
// Simulate a heavy computation or filtering
const filteredItems = Array(10000)
.fill()
.map((_, i) => `Item ${i + 1}`)
.filter(item => item.toLowerCase().includes(e.target.value.toLowerCase()));
setItems(filteredItems);
});
};
return ( <div> <input type="text" value={input} onChange={handleChange} placeholder="Type to filter..." /> {isPending ? ( <p>Loading...</p> ) : ( <ul> {items.map((item, index) => ( <li key={index}>{item}</li> ))} </ul> )} </div> ); } export default ExampleComponent;