Nm | #Question |
---|---|
1 | What is gatsby.js? |
SPA: Works by loading a single HTML page and dynamically updating the content as the user interacts with the app. Uses AJAX calls to interact with the server, fetching and rendering data without reloading the entire page.
PWA: Extends the functionality of traditional web apps with features like offline access, background sync, and push notifications, thanks to Service Workers. Can be installed on a user's home screen like a native app and can run independently of the browser.
Nm | #Question |
---|---|
1 | What is continuos deployment ( what is continues deployment)? |
2 | Git merge rebase difference? |
3 | What is cherry pick? |
Nm | #Question |
---|---|
1 | Difference beteen react context and redux |
-
Var - scope is global or function ( if var's used inside function ). Let, const - they have block scope.
if(true) { let test = 'test'; // test variable is available only inside if block }
Let - can be reasigned. Const - can't be reasigned.
-
Functional expression - function defined inside an expression. Example:
const getRectArea = function (width, height) { return width * height; }; console.log(getRectArea(3, 4));
Functional declaration - function declared with function keyword. Functional declaration creates binding of new function to a given name.
function calcRectArea(width, height) { return width * height; } console.log(calcRectArea(5, 6)););
function print() { console.log(arguments) } print(1,2,3,4); /* result below: { "0": 1, "1": 2, "2": 3, "3": 4 } */
Remember arrow function don't have acces to the arguments.
const obj = { name: 'deeecode', print: function() { console.log(this) } } obj.print() // {name: 'deeecode', print: ƒ}
You can't do smth like above with arrow function.
Arrow function - don't have binding to this ( in inherits this from outside look code example below), arguments, super and shouldn't be used as methods. They can't be used as a constructors - we can't call them with new keyword. Cannot be used as generator functions.
Explain next examples:
function Person() { this.age = 0; setInterval(() => { this.age++; // `this` refers to the `Person` instance console.log(this.age); // Correctly logs the incremented age }, 1000); } let p = new Person();
function Person() { this.age = 0; setInterval(function() { this.age++; // `this` refers to the global object or `undefined` in strict mode console.log(this.age); // NaN or throws error in strict mode }, 1000); } let p = new Person();
-
Generator is a process that can be paused and resumed and can yield multiple values. Generator returns iterable Geneartor object.
function* generator(i) { yield i; yield i + 10; yield i + 20; } const gen = generator(10); console.log(gen.next().value); // Expected output: 10 console.log(gen.next().value); // Expected output: 20 console.log(gen.next().value); // Expected output: 30 console.log(gen.next().value); // Expected output: undefined
Calling .next() returns an object in form:
{ value // current value of the iterator, done // boolean indicating if iteration is finished }
-
- What are types, when do we use it? Types are definitions of data type. Typescript compiler use it to detect errors.
- What are Tuples?
let ourTuple: [number, boolean, string]; ``
Tuples are typed arrays 4. What are Unions? A union type describes a value that can be one of several types.
javascript function printStatusCode(code: string | number) { console.log(`My status code is ${code}.`) }
5. An intersection type is a type that merges several kinds into one.interface Student { student_id: number; name: string; } interface Teacher { Teacher_Id: number; teacher_name: string; } type intersected_type = Student & Teacher; let obj1: intersected_type = { student_id: 3232, name: "rita", Teacher_Id: 7873, teacher_name: "seema", }; console.log(obj1.Teacher_Id); console.log(obj1.name)
- What are enums? When to use? Enums are collection of constants
- Types is used to type your values, to avoid errors and bugs. Here more: https://blog.logrocket.com/typescript-enums-vs-types
- Enums example:
enum Names { Vasyl, Yaroslav, Igor } var test = Names.Yaroslav;// 1
- Interface: An interface is used to define a structure for an object.
-
Map return NEW array. It doesn't modify initial array. ForEach doesn't return array. But runs function for each element of array. Foreach returns original array. Filter, slice returns new array. They dont mutate initial array.
-
- This is keyword. It refers to different objects depending on how and where it used.
- You can't change this value.
- ALone this refers to the global object. INside function - this refers to the global object also. In event handlers this refers to the hTML object.
function dotest() { console.log(this); // here we'll get Windows object }
- Call and apply methods are used to call 1 object method on another object as argument
- If yout type this in console, you will get Window object.
-
Yes setTimeout is async
-
Promise object represents eventual completion or failure of asynchronous function. Whenever tasks should be executed asynchronouslo. Promisess are used. Example login function: Promise returns fullfilled or rejected status. Promise is asyncchronous function. Promises can be handled with:
then catch:
const doPromise = () => { new Promise((resolve, reject) => { resolve({result: 5 }); }).then((data) => console.log(data)) .catch((error) => { console.error('Promise rejected with error: ' + error); });; } doPromise();
Promise.then(() => datafetch).then(result => result).catch(()=>'error fetching data')
asyn await try catch
async function main() { try { const doc = await db.doc("user/" + uid).get() if (doc.exists) { console.log("User data:", doc.data()); // use fetched data, for example in setState() } else { console.warn("No user data."); } } catch(error) { console.log("Error getting user data:", error); } }
Promise all (method) takes an array of promises and returns a single promise. The returned promise fullfills if all promises are executed, and noone fails.
const promise1 = Promise.resolve(3); const promise2 = 42; const promise3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); }); Promise.all([promise1, promise2, promise3]).then((values) => { console.log(values); });
-
- If we speak about closure , we need to mention local and global scope. Functions have its local, private scope. Variables can be global or private - depending where they'are declared.
- if variable is declared without keyword, it is global. Even if it's declared inside the function.
function doTest() { test = 5; } doTest(); console.log(test); // 5
-
- Spread operator is mostly used with arrays. It's used to efficientl merge, cop arrays, pass elements to functions.
You can use spread operator to merge 2 objects,or 2 arrays. In React you can use spread operator to pass properties to the component:
const props = {firstName: 'John', lastName: 'Doe'}; const component = <UserComponent {...props} />;
Example of copying array with spread operator:
const arr = [1,2,3]; const copyArr = [...arr]
Example of merging 2 objects:
const nameObject = { name: 'John' }; const surnameObject = { surname: 'Cool' }; const mergedObject = { ...nameObject, ...surnameObject };
Example passing arguments to functions: ```javascript function sum(a, b, c) { return a + b + c; }
const nums = [1, 2, 3]; const result = sum(...nums); console.log("Result of sum:", result); //6
rest operator can be used to extract the remaining properties. WHile spread operator used to exapand elements, rest operator used to condense elements into a single enti
const {a, ...rest} = {a: 1, b: 2, c: 3}; console.log(rest); // {b: 2, c: 3}
It helps to get all arguments into an one array named numbers:
function sum(...numbers) { return numbers.reduce((total, num) => total + num, 0); } function printNumbers(...numbers) { console.log(numbers); // } printNumbers(1,2,3,4,5); // [1,2,3,4,5]
-
Set are collections of unique values:
const testArr = [1, 2, 1, 1]; const newSet = new Set(testArr); console.log(testArr); // { 0:1, 1:2 }
if you want to convert it to the arr:
console.log([...setValue]);
Set Object provides: A size property that contains a number. A has() method that takes an element and returns a boolean. A keys() method that returns an iterator of the elements in the set.
-
Wraps code that can fail and pass error to the catch instead of crashing the app.
-
Types in TypeScript are more flexible and can define primitive, intersection, union, tuple, or different types of data, while interfaces are used to describe the shape of an object
-
Eather
const arrray = [...yourObjectCollection]; // Or make it with Array.from Array.from(yourObjectCollection)
-
it adds additional spacing
-
Eather
openMyFile(); try { // tie up a resource writeMyFile(theData); } finally { closeMyFile(); // always close the resource }
or
try { // try_statements } catch(error) { // catch_statements } finally() { // codes that gets executed anyway }
This inside arrow function is referenced, pointed to the global object. We normal function declaration - it points to the inner scope.
```javascript
function RegularFunction() {
this.value = 10;
setTimeout(function () {
console.log(this.value); // undefined, because `this` refers to the global object or is undefined in strict mode. It should be remembered that for example in chrome, it can console 10 instead of undefined ( it's connected with specific chrome console aspects ).
}, 100);
}
function ArrowFunction() {
this.value = 20;
setTimeout(() => {
console.log(this.value); // 20, because `this` is inherited from ArrowFunction's scope
}, 100);
}
new RegularFunction(); // Logs: undefined
new ArrowFunction(); // Logs: 20
```
Object assign method is used to clone or copy proeperties from 1 object to another.
```javascript
const obj = { a: 1 };
const copy = Object.assign({}, obj);
console.log(copy); // { a: 1 }
You can add 1 target object, and 2 source objects like that:
Object.assign({}, product, {
votes: product.votes + 1,
});
```
With help of Object.create we can create an object from a given prototype object. It retrns a new object with the prototype set to given object.
```javascript
const myPrototype = {
size: 'large',
getSize() {
return this.size;
}
};
const myObject = Object.create(myPrototype);
console.log(myObject.getSize()); // 'large'
```
It can also be used Object.create to create subobject, which inherits properties and methods from their parent objects.
```javascript
const mySubObject = Object.create(myObject, {
color: { value: 'red' }
});
```
console.log(mySubObject.getSize()); // 'large'
console.log(mySubObject.color); // 'red'
Object is stored and copied "by reference", whereas primitive values strings, numbers, booleans copied as a whole value.
```javascript
let message = "Hello!";
let phrase = message;
```
In the end we have 2 independent variables.
A variable assigned to an object = stores not object itslef, but its address in memory, in other words - a reference to it.
```javascript
let user = { name: "John" };
let admin = user;
```
![image](https://github.com/user-attachments/assets/b687fb14-9572-4f85-bdc9-5ca86afb1a21)
When objects are equal?
![image](https://github.com/user-attachments/assets/9f1bf005-6efc-4d44-8125-c56089341c29)
Two independent objects are not equal:
let a = {};
let b = {}; // two independent objects
alert( a == b ); // false
Outer function doesn't have an access to the inner functions. But inner functions have an access to the outer functions. It's how lexical scope does work.
-
const names = ["Rohit","Aakash","Vinay","Ashish","Vasu"]; const tes = names.forEach((item) => item + 'lolo');
Answer: it will be undefined, cause forEach doesn't return any walue, it just runs function for each element of array
-
var s = 'john smith~123 Street~Apt 4~New York~NY~12345'; s.split('~') ``
-
Count example (to get previous state we need to put callback function):
-
const test = { test: 'test '}; {...test, name: 'pame'} ``
-
Answer -setCounter should be used out of useEffect here to prevent infinite rendering problem.
-
React - is library. Main React features:
-
JSX - js extension. We can write HTML structures inside JS. For example use HTML structures inside if structure:
-
Components - we create reusable, independent components.
-
Virtual DOM - it's virtual copy of DOM, with help of it preformance is improved. With help of that we update only necessary things in DOM, not rebuilding all DOM tree.
-
One way data-binding.
-
high performance - while updating components - we don't refresh, update all application.
-
-
Children component're placed inside parent component. Data's transfered from parent component to child component. Benefits unindirectional data-flow: 1. Easy to debug - cause we know how and frome where data is coming. 2. Less errors - more control on data.
-
State in React - is object containing component an information. It can be changed. When state's changed, component is rerendered. Remember not to mutate directly React's state, cause it can lead to different problems, bugs. When state's updated, react calls render() method and component's updated.
-
Nope, it's used babel to transpile jsx code to regular JS.
-
Document Object Model - is interface that treats HTML as a tree structure, in which each node is object representing a part of the document. DOM defines a way nodes are accessed and manipulated. Virtual DOM - it's virtual copy of DOM, with help of it preformance is improved. With help of that we update only necessary things in DOM, not rebuilding all DOM tree.
React Reconciliation process of updating DOM. It updates the virtual DOM first and then uses the diffing algorithm to make efficient and optimized updates in the Real DOM.
-
- es6 ins newest version of js
- es6 has additional type Symbol
- es6 has 2 new ways of declaring variables: let and const
- es6 has arrow function
- little bit difference while importing, exporting components, declaring classes
-
Install node, instal crea-react-app. It's ready to use.
-
Event in React is action triggered on some change in the user interface. It can be click or key pressing for example. Synthetic event - synthetic event is object we get after triggering some event. An example:
<button onClick={e => {
console.log(e); // React event object
}} />
-
- Key is a unique identifier and it is used to identify whhich element of list was updated, deleted or added. Keys also help to improve performance of rendering lists.
- Index should be added as index cause, if you for example filter your list - elements of list will get new indexes - other than you initialized at first.
-
React application consists of react component. Component is a reausable piece of code. Component can be stateless or statefull.
-
You needed constructor and set value to the this.state. Now you can just use useState hook.
-
Props are short for properties. In React it's object, storing value of attributes, smth. like html attributes. We need it to pass data from component to the component. Inside component we have an access to props in similar way as we have an access to the function parameters. Props aren't mutable in React.
-
State is muttable. Props are unmutable. State refers to internal data of component. Props are date transfered from parent component to the child.
-
High ordered component is wrapper for other components. They allow to reuse some logic across different components. F.e. you want to add logger HOC, which will be loging information about mounting, demounting component. export default withLogger(SomeComponent);
What are standart lifecycle React methods?
**getInitialState()**, **componentDidMount()**, **shouldComponentUpdate()**, **componentDidUpdate()**, **componentWillUnmount()**.
UseEffect is used for handling sideEffects - like getting some data, or handling some event.
UseMemo() hook helps to cache, remember the result of calculations between rereners.
// trivial example of using useMemo
```javascript
const sortedNames = useMemo(() => {
[...someValue].sort();
}, [names]);
```
```
// if we wanna have different value of method, depending on url value:
```javascript
const method = useMemo(() => {
method: "Post",
url
}, [url]);
```
We used controlled or uncontrolled components inside form ( while dealing with inputs ). If we have input connected to the state, and handle that value. It's controlled component. Displayed data is syncronized with the state of component.
Uncontrolled components hold their state internally. And you query DOM using a ref to find its current value when you need it.
Hooks was added in React 16.8 to allow function components to have access to state and other React features. Bad practices: - dont dynamically mutate a hook, dont dynamically use hook. Example: don't push hook as prop.
-
- UseEffect allows to perform you side effects in your application ( fetchingdata, diretly update dom, setting timers).
- useEffect is called after first render, and every time component is updated.
- Difference between useEffect and UseLayoutEffect ( Useeffect runs after browser finishing painting,useLayoutEffect runs synchronically with painting browser). UseEffect has built-in error handling, so it doesn't crush entire application,whiel useLayoutEffect doesn't have it.
-
Usecallback memoizes a function definition and returns momoized function during rerenders, it improves performance in that way. If you need call function, but don't want it toretriggered in useEffect, then you will need useCallback. If we want to pass some function, to the component, and we don't want that component to be rerendered. Then can use useCallback. Example:
-
- UseREf is hook, which we need if we want to operate directly with DOM.
- Example of use: if we need for example some input in form to be auto focused. We need to find that element in DOM and autofocus.
- UseReff return object with current property.
const refValue = useRef(0); // this will return { current: 0 } object.
-
With help of both you can save some value. Whatever you store in useRef is not reactive, it means it will not cause component rerender.
-
React context is alternative to the 'prop drilling' ( passing data from parent to children ). Context is often consideredas lighter, simpler solution to using Redux for state management. With context API we have 1 store where all data is passed to and from all data is extracted from. Example of data stored in context: template language, user authentificated data. ANother good example is dark mode - if you want an access to it from each component.
-
You need specific folder for your components ( it can be also seperate folder for your common components ), for hooks, constants. It's good to have proper structure - it's easier to find what you need, it's easier to make onboarding for new team members. It's god to use absoolute imports.
-
- YOu can use e2e tests ( when you test your whole applications ( all components connected 1 to another) on real scenarious, data ). You can also make unit tests ( when you testing behaviour of each component)
- We use react-test-library and react-test-renderer ( to render yoru components to js objects ). You operate on real DOM, while using this library. You can find element by role or by data-testid. It can be also simulated events with help of that library.
-
React dev tools is extension, it can be installed for any browser. As rule we use it if we have some problem with performance ( for example component is rendered too many times ).
-
- React portals let you render some component outside your normal react component structure.
- Example: you can use it for creating modals.
- portal will not inherit parent css styles. Remember using stopPropagation() - event emmited from a portal component - will propagate to the Reactt tree and trigger event on ancestor component. Example createPortal:
-
- Imagine you have component, that appears afoter in some scenarios. It's allways displayed in your app. But it still exists in your bundle. To fix it you can use lazy loading or dynamic imports.
- Below you can see lazy loading of component. Now inside our component we can use it with react suspense.
- Example of dynamic import: if some condition is met, then we import our component: Here you will have error, cause you can't render Promise with appropriate handling of it. Acually its why is better to use lazy loading - it handles Promise issue of importing components.
-
- Splitting code is technique which allows to optimize the performance of React application. With help of it you can split your code into smaller chunks and loading the on-deman. You can reduce load time. React provides built-in tools. Like lazy, suspend.
const SomeComponent = React.lazy(() => import('~/components/SomeComponnent')
- SUspense let you load fallback, while yoru children components are loading.
- One more way - is using dynamic imports ( for example for functions ).
-
- SSR - Server side rendering. CSR - CLient side rendering.
- Gatsby.js and Next.js supports both CSR and SSR.
- Static Pages are built during build time. SSR allow to render a page during run-time. You can deal with data that is fetched when a user visits the page.
- 1 of the most importa benefits oF SSR can be improving performance of your website. You can reduce the amount of work the users's browser needs to do.
- Practical example: you need to call some script and add smth to the header only after some behaviour user on page. In gatsby.js pages are rendered statically during build, to do smth like that you need SSR.
-
Fragment alows you to return group ofchildren elments without need of extra DOM component.
-
Your effect will run only after initial render.
-
Hooks are reusable functions. Example: hook for fetching data, or another example hook for recognition screen size.
-
Hooks are reusable functions. Example: hook for fetching data, or another example hook for recognition screen size.
-
solution: it's better to drop it in 1 useEffect and handle different cases. Or you can drop it in distinct function.
-
Observer patterns - it's actually using state in React. When state data changed, component ( dependent properties ) are updated. Singleton Pattern - singleton pattern, when global state is shared across the application.Singleton can only have 1 instance. Proxy pattern - For example handling lazy loading of images. Example: when you have RealImage class, but access to it provides ProxyImage class.
class RealImage { display() { console.log("Displaying the real image."); } } class ProxyImage { constructor() { this.realImage = new RealImage(); } display() { console.log("Loading the image..."); this.realImage.display(); } } const image = new ProxyImage(); image.display();
-
1 of possible solutions: You can set some flag with help of localstorage f.e. after you fetch data. And the you check if this flag is true, if it's you aren't fetching data 2nd time.
-
It's better use controlled components - assign some 'handleChange' function, and control state of input inside it. It's better approach for testing, debugging approaches.
Monorepo - its one repo, containing multiple applications, projects with well defined, structured relationships.
Polyrepo - a repo for each team, application, project. It's often has a single build artifact, and simple build pipeline. Build artifact - files produced by build ( different logs, reports, distribution pacakgs ).
1. Is **Monolith** same as monorepo? No, monolith itj just repository containing a application, but there is no well prepared dependencies, it's not wel structured and encapsulated.
2. What is advantage of **polyrepo**? With help of it we can keep team autonomy. You can decide what you do with your repo, who can have access for it, when to deploy it etc.
3. What is disadvantages of **polyrepo**?
- problem when you want to share code betweend different repos;
- problems with compability of third party libraries;
- time consuming configuration of each repo and synchronizing it.
- if each team works only on 1 repo, code can be repeated etc; its easier to standartize work of teams.
- if we have some share repo, library and you need to make change, it should be tested change for reach repo.
- each repo can have different settings tools
- it can be problem to use projects like that.
4.What are advantages of **monorepo**?
- easy to create new project;
- it's easy to test your change for different packages or applications.
- it's better developer mobility and performance while working on monorepoy
- all projects inside monorepo using same versions of thirls party libraries;
- atomic commits - you dont need different projects, apps dependency after each commit, change
Advantages of microfrontends ( polyrepo ):
![MicroServicesIamge](https://github.com/user-attachments/assets/e5049a98-d0cb-4fdd-a965-48f63f4456fe)
1. Independence and autonomy - teams can work on different parts of the frontend without interfering each other. Each team can use its own stack, library, deployment pipelines.
2. Technology diversity - freedom to choose any technology.
3. Resilience and fault isolation - if one micro fails, it doesn't bring down the entire application.
4. Its easeier to maintain test and refactor distinct micro frontend.
Webhooks - automated messages sent from apps when something (event) happens. Example payPal sends you notification, when some of clients payed you some money. OR when some ecomerce shops notify you when you have some new order. It's a way one app push automatically notifications to other app.
- what is difference between webhook and API? To put it simply - API does stuff when you ask it to. Webhooks does it when some situation, event is triggered. We can say it works on its own.
-
- Babel is transpiler, with help of it developers can use newest features of language.
- Babel configuration. You need node.js, npm. Later create configuration file, babelrc. NExt install plugins, presets. And finally creating build script.
- Source target difference. Source - code written in a way Babel can understand it, target - code that should be in the end as output.
- How to configure babel for a specific framework? Each framework like react or angular has its own preset. Preset-react, preset-angular etc.
- @babel/runtime - helpers for optimisinig babel work. It helps for example to exclude repeatable code.
-
Time complexity. It calculates amount of time it takes to run an algorithm.
- O(1) - constant. Run time is independent - we don't worry about the input size. Examples: accessing an Array Element, REtrieving a Value from object. Retrieving element of array or object takes constant times.
- O(n) - linear time algorithm - execution is proportional to the input size.
- O(n²) - quadratic algorithm - number of steps is square root of input size. For example if we have for loop inside another for loop, and these loops're manipuating on the same input.
Space complexity - amount of memory space required to solve some problem/algorithm. Examples:
- O(1) - constant. Run time is independent - we don't worry about the input size.
function add(n1, n2) { const sum = n1 + n2 return sum }
Space complexity is constant. Cause input is constant. We'll always get 2 parameters.
- O(n) - Linear. Space complexity is increasing depending on parameter length.
function sum(arr) { const sum = 0 for (let i = 0; i < arr.length; i++) { sum += arr[i] } return sum }
It can be also logarithmic O(log n) time complexity or quadratic O(n^2) f.e.
Next.js, Gatsby.js.
- Continuous integration refers to the build and unit testing stages of the software release process ( you can implement it with jenkins for example in your project)
In OOP, the fundamental basis is classes, instances of which can be stored in variables. In functional programming, however, there are no variables; there are functions and functions only.
Dependencies are crucial for your production build. While Devdependencies are needed only while dev work, but we don't need in production build.
When you run npm run typecheck or yarn typecheck, the TypeScript compiler will analyze your TypeScript code and perform type checking based on your type annotations and configuration
This option specifies the file extensions that Babel should consider for transpilation
This line cleans all transpile files inside chooden folders, to make sure project runs properly and without transpilesd files leftovers.
Markdown - markup language used to add formatting for your text ( healdlines, lists etc. )
Web components - it helps to create reusable, encapsulated HTML elements. Key features: creating custom element, shadow dom ( scoped style, eventy ), html template. You have alss lifeceycle methods, you can cahange attributes etc.
***Lit library*** - is library for building web components. It's fast and provides reactive compnent ( components are automatically updated after data change ).
It has shado dom suppoort, lifecycle managements, typescript support etc.
![litComponentExplain](https://github.com/user-attachments/assets/8cd45ee5-13ce-46da-84b4-a3d4f894aaf3)
1. Property - iit's like external prop
2. state - it's something like react state
3. Callback - it's lifecycle method.
-
Forms Api - helps validate forms.
History API - accessing windows.history object.
const inpObj = document.getElementById("id1"); if (!inpObj.checkValidity()) {
Web Storage API - geting, setting storage.window.history.back();
Fetch apilocalStorage.setItem("name", "John Doe"); localStorage.getItem("name");
Geolocation apifetch(file) .then(x => x.text()) .then(y => myDisplay(y));
Other examples: window.location, window open etc.... navigator.geolocation.getCurrentPosition ...
-
- Clean html - check if app has appropriate html5 tags
- Reduce number of server calls if possible - lazy loading for example
- Css - prefetch fonts for example, check if there is no leftovers in css, simplify selectors. Splitting css modules - css that we don't need on page loading. Can be loaded later.
- Optimize videos, images - compress size, resize for different viewports, lazy loading.
- Prefetching in front-end development is a performance optimization technique that involves loading resources (like data, images, scripts, or other assets) in advance, before they are actually needed by the user.
- Caching - in next.js, gatsby.js it's is configured by the default.
- Code splitting - is the practice of splitting your codebase into multiple bundles or chunks that can be loaded on demand, rather than loading the entire codebase at once.
-
- Question answer:
- CSP - setting csp data in meta tag, header.It helps against Cross-Site Scripting and data-injection attacks.
- Keep authorization data in env variables.
- Most commont types of attacks: Malware, cross-site scripting, data-injections, DOS ataki ( it depends alot what is your server capable of ).
- question naswer: IT can be posted some content, script, maleware to the form if it's not sanitized.
-
- semantic html
- keyboard navigatoin ( tabindex)
- color contrast, focus contrast
- text alternatives for images , aria-labels for buttons forms
- responsive images
- aria links, CEO settings
-
- SOLID 1. Component or function should have oneresponsibility, purpose 2. Open for extension 3. Subsitituion Principe - input should work with all types of input. 4. Interface Segratgateion Principle - dont pass something, you dont need to component. 5. Dependency inversion - high level modules should not depend on low-level modules directly. here more Info: https://chatgpt.com/c/66d99613-6570-800c-8416-bd259966b6a3
- Clead readable code
- Component designs - sepearate login, view in different files. Dont-write to larga components
- Avoid rerenders, implement lazy loading.
- Accessibility
- Testing debugging
- Avoid inline javascript and css
SPA Works by loading a single HTML page ( file) and dynamically updating the content as the user interacts with the app. Key parts: - onlly parts of application are updating, refreshing not the whole application - less loading - better user experience - SPA: gamil, google maps, twitter - there is probles with SEO - cause it's all 1 file and dynamic reloading of content. IT's why sometimes google has problem with crawling such site.
PWA Extends the functionality of traditional web apps with features like offline access, background sync, and push notifications, thanks to Service Workers. Can be installed on a user's home screen like a native app and can run independently of the browser. Examples: spotify, uber, telegram, PWA
SPA renders pages on client side. Content is updated without reloading pages. Single html file. Problems withs SEO. Best suited for dynamic, highly interactive applications like dashboards, social networks, or apps that need frequent, real-time updates. GATSBY, NEXT are SSG ( static site geeneration ) - pages are served as statisc files, it's super SEO friendly, provides benefits of both spa and server-rendered pages. Good SEO. Ideal for content-heavy sites, blogs, marketing pages, or e-commerce sites where performance, SEO, and fast initial loads are crucial.
The most important difference is - localstorage has bigger capacity ( 5mb), while cookies have only 4kb. In cookie we can save some small data, like info about user session durability. In localstorage we can store bigger chungs of data.
-
-
Webpack is a tool for configuration your project environment, it helps to bundle your project modules.\
-
In dev we want features like:
- strong source mapping - allows developers to see the original source code (e.g., TypeScript, SCSS, or ES6+) in the browser’s developer tools instead of the compiled or minified code that is actually running in the browse. Frameworks like gatsby.js, next.js have it by default.
- Localhost, live reloading, hot moudle replacement - monitoring chamges, updating modules, replacing moudules, callback execution.
- Envrionment variables. So dev is about dubugging,efficient workflow.
In prod we focus on:
- minifiying and optimizing sources, files, assests.
- code splitting - create smaller chunks, and load them if only you need it.
- Tree shaking - removes unused code.
- Ensure that any debug or tet code is stripped out and not included in production mode.
-
Frameworks like gatsby.js, next.js have its own webpack.config. But both that framework allow to add your own additional webpack configurations.
-
"build": "webpack --mode production" - result will be file main.js in your dist folder. In the end you will get main.js file with minified, optimized code. process.env.NODE_ENV - in that file will be set to the 'production' mode.
-
You can create it manually or you can use npm init command.
React testing library works on real DOM. You can find form elements by their label text, finding links and buttons from their text. You can use also datatest-id in places, where you can't use other methods.
Render method is used to render component, screen method is used to find element, what you need by role, label or testid.
Advantages of react query: - simplified data fetching; - caching; - updating data in background
box model - it's box which wraps every HTML element. Box model consists of content, padding, bordery, margin.
- Picture and source are used if we want to add alternative versions of image depending on size of screen for example.
- The viewport is the user's visible area of a web page. The viewport varies with the device. - we set width of peage to follow screen-width of the device. Initial-scale=1.0 defines zoom defult level.
- Relative, absoulte, static, fixed, sticky.
- Id, Classs, Element, * - all. We have also Descender, children sibling selectors.
- Rem - dictate an element's font size relative to the size of the root element. In most cases 16px is default. 1 of the most valuable advantages of rem is scalability and consistency.
REACT REDUX STATE MANAGEMENT LIBRARIES
- Context react is more useful when you work with simple application. Redux is used when more complicated cases, applications.
What is cookies, sessiens, tokens what is turborepo in few words
What is Encapsulation https://www.linkedin.com/pulse/what-encapsulation-javascript-amit-kumar/ https://dev.to/kozlovzxc/js-interview-in-2-minutes-encapsulation-oop-2ico
arrow function with normal functino difference: https://bootcamp.uxdesign.cc/arrow-functions-vs-regular-functions-in-javascript-29db7928d696
preventDefault(): Prevents the default browser action for the event. stopPropagation() - difference
///////////// react exercises :
// create a simple react app that display a list of countris and their capitals // requiremeites: // the list of countries and capitsls should be fetched from the API // the list should be displayed in the CountiriesPage // each country should be displayed in a seperate component // the user should be able to filter the list by capital
const BASE_URL = "https://restcountries.com/v3.1/all";
/**
- To filter by capital city, use the '/capital/{capital}' endpoint */ const FILTERABLE_CAPITALS = [ "Talinn", "Helsinki", "Stockholm", "Oslo", "Copenthagen", "Reykjavik", ];
//////////////
////// How to pass data from child to parent:
//////
Gatsby.js is framework - used to generate static pages during build. Main feautres of gatsby.js: - it's based on React.js - it used Graphql to plull data nad structure it.
Continuos deployment - software development practice where code changes are automatically deployed to a production envrionment after passing predefined testing and qualisty assurance stages. It helps to reduce manual intervention and to ensure new code (feats, fixes etc) are delivered to users as quickly as possible. You can configure it in netlify for example.
-
merge - combining changes from one ( source branch) into another branch ( target branch). It combines history of 2 branches. Git merge pulls in the latest changes from main into the feature branch creating a new "merge commit" in the process. Use merge if you need to keep, save history of both branches. Whe fewe people collaborates on same branch. See example below:
rebase - is moving the changes from one branch onto another branch. It puts commits from one branch to another in linear way. See below:
Use merge if you need to keep, save history of both branches. Whe fewe people collaborates on same branch. Use rebase if you you want clean, linear project history. Use it to update branch with the lst changes from min branch before merging.
Below you can see difference between git merge and git rebase. Main difference is while you doing rebase, you keep consisten commit history.
In simple terms, git cherry-pick picks a specific commit from one branch and apply it to another branch without merging the entire branch.