React Notes
React
What is React?
- React is a declarative, efficient, and flexible JavaScript library for building user interfaces.
- It allows the creation of complex UIs using small, isolated pieces of code called "components."
- Created by Jordan Walke, a Facebook programmer.
- Often used for creating Single Page Applications (SPAs).
ES6 Knowledge Required
React uses ES6, so familiarity with the following topics is necessary:
- Classes
- Arrow Functions
- Variables (let, const, var)
- Array Methods like .map()
- Destructuring
- Modules
- Ternary Operator
- Spread Operator
Origin of the Name "React"
- The name "React" suggests that the library reacts to changes in data.
- The main idea is to construct a UI that dynamically reacts to data changes without manual DOM (Document Object Model) manipulation.
- React tracks the application state and automatically updates the UI when data changes.
Example
import React from "react";
import ReactDOM from "react-dom/client";
function Hello() {
return <h1>Hello World!</h1>;
}
const container = document.getElementById('root');
const root = ReactDOM.createRoot(container);
root.render(<Hello />);
How React Works
- React creates a VIRTUAL DOM in memory.
- Instead of directly manipulating the browser DOM, React creates a virtual DOM in memory, where it performs all necessary manipulations before making changes to the browser DOM.
- React only reacts to changes that require updates.
- React identifies the changes made and updates only what needs to be changed.
- The Virtual DOM finds the best way to apply all changes to the page, minimizing DOM interactions.
- This makes React efficient and optimized; developers don't need to worry about the underlying mechanisms.
DOM
- Presents a DOM structure example with HTML elements such as
html,head,meta,link,body,div,p,span,img, and their corresponding styles defined in CSSOM. - Illustrates how the Render Tree is constructed based on the DOM and CSSOM, including only the visible elements.
How it Works - DOM
- Critical Rendering Path:
- HTML is parsed to create the DOM.
- CSS is parsed to create the CSSOM.
- JavaScript is executed.
- The Render Tree is constructed.
- Layout is performed.
- The page is painted.
Virtual DOM
- A virtual representation of the actual DOM.
- It's a lightweight copy of the real DOM that exists in memory, not in the browser.
- When an application change occurs, the changes are first applied to the Virtual DOM.
- The Virtual DOM calculates the differences between the current and new versions (known as diffing), and only updates the parts of the real DOM that have changed, improving efficiency.
Comparison
- DOM is heavy and interacts directly with the browser.
- CSSOM complements the DOM, handling styles, which can be costly to update.
- Virtual DOM is a lightweight, intermediate step that enables more efficient change management, minimizing direct operations on the real DOM.
- Virtual DOM optimizes UI update processes by minimizing direct manipulations of the actual DOM, thus increasing application performance.
React Application
- React is designed to update the DOM in a web browser.
- Developers don't need to handle complex issues related to creating high-performance single-page applications, as React takes care of it.
- With React, there's no need to directly use the DOM API; developers provide instructions on what to create, and React handles the generation and connection of the elements.
Using React with CDN
- Example of using React, ReactDOM, and Babel from CDNs to create a simple "Hello World" application.
Checking if React Works
- Verifying the availability of React and ReactDOM objects in the browser's console, including their properties and methods.
React.createElement
- Creates a React element, an alternative to JSX.
- Syntax:
createElement(type, props, ...children)
Example of React.createElement
- Illustrates how to create a React element using
React.createElementto generate a div with the class "player" and the text "Robert Lewandowski".
Child Elements
- Child elements in React are generated using
props.children. - Demonstrates creating a list (
<ul>) with list items (<li>) usingReact.createElement.
Result
- Shows the structure of the React element created for the list, including the
$$typeof,type,key,ref, andpropsproperties.
Looping with .map()
- When creating a list of child elements from an array, it's beneficial for React to have a
keyproperty on each element. - The
keyproperty helps React efficiently update the DOM. - The index of the array can be used as a unique value for each component.
Nesting
- Demonstrates nesting React elements using
React.createElement.
React 18
- In React 18,
createRootis used; the previous syntax generates a warning. - Example shows creating a React element and rendering it using
createRoot.
Sandboxes structure
- Using codesandbox.io to create a React application.
- Files: App.js, index.js, styles.css, package.json
Setting Up the Environment
- Node.js must be installed.
- Use
npx create-react-app projekt1to build the React application structure with the nameprojekt1. - Currently, it's better to use Vite:
npm create vite@latest.
After Creation
- Project structure in Visual Studio Code, including directories and files like
node_modules,public,src,App.js,index.js, etc.
How to Run?
- Navigate to the created project folder in the terminal:
cd projekt1. - To run the application, type
npm start.
App.js File Content
- Shows the default content of the
App.jsfile in a new React application.
Alternative Approach
- Remove the entire contents of the
srcdirectory and create anindex.jsfile with custom content.
Version 18
Previous syntax:
javascript import ReactDOM from 'react-dom'; ReactDOM.render(<App />, document.getElementById('root')); From version 18:
javascript import ReactDOM from 'react-dom/client'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(<App />);
Rendering HTML
React renders HTML on a web page using a function called
createRoot()and itsrender()method.Example:
javascript const container = document.getElementById('root'); const root = ReactDOM.createRoot(container); root.render(<p>Hello</p>); Typically, the
divelement where HTML is rendered has the idroot.
Table Example
- Demonstrates creating a table using React elements.
JSX
- React uses its own markup language called JSX, an extension of JavaScript with XML-like syntax.
- JSX allows writing HTML elements in JavaScript and placing them in the DOM without
createElement()orappendChild()methods. - JSX simplifies React application development.
Example
With JSX:
javascript const myElement = <h1>I Love JSX!</h1>; const root = ReactDOM.createRoot(document.getElementById('root')); root.render(myElement); Without JSX:
javascript const myElement = React.createElement('h1', {}, 'I do not use JSX!'); const root = ReactDOM.createRoot(document.getElementById('root')); root.render(myElement);
Another Example
- Shows an example of using JSX to create a React element.
Babel
- To use the latest JavaScript features with JSX, modern source code needs to be converted into a format that web browsers can interpret.
- This process is called compilation and is performed by Babel.
What Babel Did
- Shows the generated JavaScript code after Babel compilation.
Expressions in JSX
JavaScript expressions must be written inside curly braces
{}.Example:
javascript const myElement = <h1>React is {5 + 5} times better with JSX</h1>;
HTML Code in One Element
HTML code must be wrapped in a single element.
Example:
```javascript const myElement = (
I am a paragraph.
I am a paragraph too.
); ```
Class Attribute
Because
classis a reserved word in JavaScript,classNamemust be used instead.Example:
javascript const myElement = <h1 className="myclass">Hello World</h1>;
Conditional Statements
- Demonstrates using conditional statements in JSX.
Components
- Components allow reusing the same structure with different datasets.
- There are two types of components: class components and function components.
- Older React codebases often use class components.
- It is now recommended to use function components with hooks, introduced in React 16.8.
Class Component
- The component name must start with a capital letter.
- The class component must include an
extends React.Componentstatement. - This statement creates inheritance from
React.Componentand gives the component access toReact.Componentfunctions. - The component requires a
render()method, which returns HTML code.javascript class Car extends React.Component { render() { return <h2>Hi, I am a Car!</h2>; } }
Function Component
- The component name must start with a capital letter.
- A function component is similar to a class component but contains less code.
javascript function Car() { return <h2>Hi, I am a Car!</h2>; }
Rendering a Component
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Car/>);
Updating a Rendered Element
- The only way to update the UI is to create a new element and pass it to
root.render().
React Only Updates What's Necessary
- React efficiently updates only the parts of the DOM that have changed.
Properties in Functional Components - Props
- Props are like function arguments, allowing data to be passed into the function.
- Example: Passing a
colorproperty to theCarfunction.
Props - Another Example
- Demonstrates passing a
nameproperty to thePlayerfunction component.
React Props
- Describes using props to pass data to a functional component.
More Properties in a Component
- Shows how to pass multiple properties to a component and use them.
Components in Components
- A component can consist of other components.
Extracting Components
- Breaking down a complex component into smaller, reusable components.
After Extraction
- Shows the code after extracting the components.
Components in Separate Files
- Demonstrates how to create components in separate files and import them.
Passing Data to Components
- Shows how to pass data to components using props.
Passing Variables
- Demonstrates passing variables as props to components.
Extracting Data From An Object
- Demonstrates extracting data from an object and passing it as props to components.
Passing More Data
- Shows how to pass multiple data points as props to components.
Passing an Object
- Demonstrates passing an entire object as a prop to a component.
Profiles, Avatars
- Illustrates how to create reusable components for avatars and profiles.
onClick Event
- Explains how to use the
onClickevent in React.
Example
- Demonstrates using the
onClickevent to display an alert.
Passing Arguments
- Shows how to pass arguments to the
shootfunction when using theonClickevent.
Conditional Statement Props
- Shows how to use conditional statements to render different components based on props.
&& Operator
- Conditionally rendering a component using the
&&operator.
Ternary Operator
- Using the ternary operator to conditionally render components.
Array Operations
- The most preferred method is
map.
Keys
- Keys allow React to track elements. This way, if an element is updated or removed, only that element is re-rendered instead of the entire list.
- A missing unique key generates a warning.
Hooks
What are Hooks?
- Hooks were added to React in version 16.8.
- Hooks enable functional components to access state and other React features.
- Class components are generally no longer needed.
- There are no plans to remove classes from React.
- They are functions that allow the use of React features, such as state and lifecycle methods.
- They enable shorter and simpler components, improving performance and simplifying state management.
useState
useStateis a hook called inside a function component to add local state.- React preserves this state between re-renders.
- It must be imported before the component definition.
useStatereturns a pair: the current state value and a function to update it.- The only argument of the
useStatefunction is the initial state. - Example:
const [color, setColor] = useState("red");
Example - useState
- Demonstrates using
useStateto manage a favorite color.
Example Read
- Demonstrates reading the value of useState.
Update State
- Demonstrates updating the state using the
setColorfunction.
Update Re-Render
onChangeis triggered with each character typed.- The component state changes, causing a re-render.
Counter
- Using
useStateHook to Manage the numeric state.
Updating Based on Previous State
- Shows the issue of incorrect state updates when relying on the current state directly within multiple
setNumbercalls.
Correctly Updating
- Shows how to correctly update the state by using a function that receives the previous state as an argument.
How it Works
- Explains how React queues state updates and applies them correctly using functional updates.
Multiple useState Hooks
- Demonstrates using multiple
useStatehooks in a single component to manage different states.
State as an Object
- Illustrates how to group related state variables into a single object using
useState.
Updating State in Object
- Shows how to update a specific property of the state object using the spread operator.
Updating States in Array
- useState used with Arrays.
Deleting elements from array
- useState used to enable deletion of elements from array, using their index as reference.
Clock
- useState used to create clock component that displays real time.
Passing Data from Child to Parent
- useState used to create a two components, a parent and a child where by clicking a butto on the child component it updates the parent state.
useEffect
- Handles side effects.
- Examples of side effects: fetching data, DOM updates, and timers.
useEffecttakes two arguments: a function and an optional dependency array.useEffect(<function>, <dependency>)- It's executed after the component renders.
Running Code on Mount
- useEffect with an empty array of dependancies, that way, run only when the component is created and mounted.
Updating State
- useEffect that run on every state updates.
Cleaning-Up Code
- useEffect and cleaning up code example, where console logs appear based on the mount unmount of the React component.
Showing and Hiding a Paragraph
- useEffect and cleaning up code when a paragraph shows and unshow, the dependencie array is empty, meaning that the useEffects run on mount and unmount of the component.
Changing Dependencies, the cleanup function runs before the new effect
What Happens Here?
- useEffect run in a loop
Fixed
- clearInterval clear any interval, and prevents looping
Countdown
- Fixed version.
What For?
- Fixed react strictmode prevent looping
StrictMode
- React StrictMode is a tool provided by React to help developers identify potential problems in React applications.
- StrictMode can introduce changes.
- Double rendering: StrictMode doubles the component rendering process to detect potential side effects. This means that components will be rendered twice. Double rendering can affect some features that rely on single rendering.
- StrictMode is mainly intended for use in a development environment and should not affect production.
Example - Counter Counts Infinitely
- Problem with StrictMode and the effect running in an infinite loop
Conditional useEffect
- The second parameter allows useEffect to depend on specific state changes.
useEffect Cleanup
- Code clearing useEffect
Clock
- Creating Clock that uses useEffect, that keeps update the time and the page time.
AddEventListener
- useState used with event listener.
- It is not recommended to use JS mechanisms in React!
Fetching Data
- useEffect used to fetch data into the screen
Another Fetch Exmaple with AbortController
Task for Practice - Fetch
- Fetch
Summary of useEffec
- Different scenarios where useEffects run, based on dependencies
### UseEffect
* UseEffect summary
FORMS
- React Forms with controlled components
Input Example
- Building an input with useState and changing the value.
Input onChange
Submit Form
- Creating form, that submits the form value onChange
From as Two Filed
- useState for the form and the two fields
HandleChange Function
Sending via post
- POST request for local API
Hook UseForm - simple form validation
- Add validation with useForm lib
npm command
- Shows intalation command.
Add All Code
Add Validation
Other Example
Routing
- Routing to enables navigate for the pages.
Add All Code
Version 6.4 Changes
- Changes from React 18 and 6.4 with the new version code.
Easy Implemented code
Nesting
- WebsiteLayout and Outlet used to enable the routing on the page.
Layout Page
Add new Page from Profil
Use Params
- Add params to enable renderind the use selected.
Use SearchParams
- Enable the search params using the URL
Prop Drill
React Context
- React Context provides a way to pass data through the component tree without having to pass props down manually at every level.
Context Provider
useContext Hook
Bottom Component
useRef - Intro
useRef Hook
useEffect where useRef is used to count from 0.
Accessing DOM Elements
- In React, we can add a ref attribute to an element to access it directly in the DOM.