Nm | #Question |
---|---|
1 | What is react native |
2 | How create class names, styles in react native? |
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();
So arrow functions do not have their own this. Instead, they inherit the value of this from the surrounding (lexical) context, which means the value of this is determined by where the arrow function is defined, not by how it is called.
1 more example: normal function:
const obj = { name: "Alice", greet: function() { console.log(this.name); // `this` refers to `obj` } };
arrorw function:
const obj = { name: "Alice", greet: () => { console.log(this.name); // `this` does NOT refer to `obj`, but to the surrounding context (possibly `window` in non-strict mode or `undefined` in strict mode) } };
obj.greet(); // Output: undefined or global object, because this
is inherited from the lexical scope
```
obj.greet(); // Output: Alice
-
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. Both're used to define type of data. 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.
- Record is a utility type in TypeScript that constructs an object type with keys of type K and values of type T. An example: Record<string, any> is a mapped type that creates an object type where the keys are strings, and the values can be of any type. So, generally speaking, Record is type that helps to define an object with specific keys and values.
-
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. The this keyword refers to the context where a piece of code, such as a function's body, is supposed to run.
- 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
Examples of global scope: window does have global scope. Variable declared with var outside of the fnction has global scop.e
-
- 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. So generally speaking we need it to handle errors.
-
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 Yes you can use types to define typf of object.
// With interface interface Base { id: number; } interface User extends Base { name: string; } // With type type Base = { id: number }; type User = Base & { name: string };
-
Eather
const arrray = [...yourObjectCollection]; // Or make it with Array.from Array.from(yourObjectCollection)
In JavaScript, collections refer to data structures that store multiple elements or values. Examples include arrays, objects, maps, and sets
-
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.
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.
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 new 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.
-
Function runs as soon as it's defined.
(function () { // … })(); (() => { // … })();
When to Use IIFEs: Creating private scope for variables. Avoiding global namespace pollution in scripts. Simulating modules or public/private APIs in legacy code. Executing setup or initialization code immediately.
-
Module exports - is a way to expose functions, objects and primitives from module, so they can be used later in your code. An example: And if we need to import it, we do it that way: Module has different properties, one of them is exports, if you will do console.log(module).
Remember also yuo have 2 other options ( its expecially often is used in React.jss) export default and export.
A module is a chunk of code in an external file that performs a specific task or function. It is a separate entity within a program, allowing for modularity and code reusability. By encapsulating related code into modules, developers can organize their programs more efficiently and make them easier to maintain
-
IN js when we pass a function by reference it is automatically called with the argument that the previous 'then' resolves to. JavaScript functions are first-class objects, meaning:
Functions can be assigned to variables or properties. Functions can be passed as arguments to other functions. Functions can be returned from other functions.
What is "Reference"? A reference is essentially a pointer to the actual location of the function in memory. When you pass a function to another variable or as an argument, you're providing access to the same function, not creating a copy.
-
Yes, before sending json to the server. You should convert it to the string.
-
Anonymous function - is function declared without function name.There is 2 different ways of using it.
-
The nullish coalescing (??) operator is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.
-
Defer attribute is useful when script is using for DOM manipulations. Means script will apply on document html. Async attribute is useful when script is not using for DOM manipulation. Some time you need script only for server side operations or for handling cache or cookie but not for DOM manipulations
-
Script tag is used to load some javascript code into your page.
-
Inline javascript is used directly in your html. External JS is contained as a sepearate file. External scripts is preferred - cause it can be cached by the browser and reused across multiple pages.
-
We can test if a scripthas loadded successfully by checking if a global variable or function defined in the script ia available.
-
WE can prevent the browser from caching a js file by providing some unique query string to the URL of the file. An example:
<script src="hellojs.js?v=1"></script>
-
It can be used Require.js or webPack for example.It provides advanced functionality for loading and managing Javascript files such as lazyLoading, dependency management, error handling.
-
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.
Generally speaking, any time a component needs to hold a dnynamic piece of data - you need a state to use it.
-
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.
- Yes value returned by useRef hook is mutable. With help of 'current' property you can modify ref data. UseRed doesn't cause component rerender.
-
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.
export const LevelContext = createContext(1); // now context has default value 1
If you don't provide provider with specific value, all your components will get thi 1 default value.
Context also lets you read info from components above. For example let's imagine you have structure like that:
It can be provided context like that. So in that way you don't need to provide context info for each specific section component.
Real life cases: 1) if you need to keep info about theme (f.e. dark/light). 2) Keeping info about logined/authorised user 3) With help of context are handled routing - active route in most cases. 4) it can be used to pass state to distance children.
-
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.
-
Reeact custom hook used to work with reused stateful logic. While service is used when you need something independent from react. Service can be used in next cases: Managing API requests and responses. Storing business logic that can be shared across the application (not just in React components).
-
Virtual dom - The Virtual DOM is a tree of JavaScript objects that represent the real DOM elements Shadow dom-is a form of encapsulation on our element. In simple words, Shadow DOM is a way to create a "mini DOM" inside a web component that is hidden and separated from the rest of the page. This means that the styles and elements inside the shadow DOM are encapsulated (protected or isolated) so they don’t get affected by, or affect, anything outside of it
-
At first we creating elment with React.createElement() then we render it with ReactDOM.render(ourElmenet, mountElemnent). Now is used jsx. Youjust render elment in that way: function renderElement() { return
}. Main reason why it's better- it's syntax. You can create element a lot easier.test
-
We dont use react proptypes ( which were running during runtime ). Cause in new projects we can use typescript and static types in development process.
-
Event handler - is function which is called on some action inside our component. F.e. onclick or onchange
-
When to Use forwardRef You need direct access to a DOM element in a child functional component. Your component serves as a wrapper for other components, and you want to ensure the ref reaches the underlying DOM node. You are working with third-party libraries or animations that require direct DOM access. You are building reusable, customizable components where consumers might need ref access.
-
Redux is library for managing global application state.
-
Actions are plain objects with a type field, and describe "what happened" in the app Reducers are functions that calculate a new state value based on previous state + an action store runs the root reducer whenever an action is dispatched dispatch is a function to update the state. Dispatching is smth like calling, triggering an event. In another words "something happened and we want store konw about it".
Simple illlustration (cake shop scenario) to show what are core redux concepts ( action, store, reducer ):
Redux uses 1 way data flow through app structure.
When something happens in the app: The UI dispatches an action The store runs the reducers, and the state is updated based on what occurred The store notifies the UI that the state has changedv Graph describing redux technology:
-
Redux - library for managing global state. It's main source library. We should use redux if we have large application state that is needed in many paces of app. Redux-toolkit - its abstraction ( set of tools ) over redux, it simplifes redux develpment by reducing some code. It provides utilities like createSlice, configureStore, creatAsyncThunk for easier state management. It helps also to reduce boilerplate code. React-Redux - it's additional library. It helps to connect Redux to React components, allows to access Redux state and dispatch actions within React app using hooks like useSelector and useDispatch.
You can combine Redux-toolkit with React-redux it's common pattern for React applications. As you can see we have react library and redux library. Ract-redux is smth like bridge between that 2 library. It's binding library for React and Redux.
3 core react principles:
- We have global state of app that is stored as an object inside a single store. We have cake shop with number of cakes: 10.
- The only way to to change the state is to dispatch an action ( we should define type ). Make an order, our action will be CAKE_ORDERED.
- How should state be updated? - with help of reducer. Reducer is shopkeeper, will take cake, reduce one and print invoice. Illutstratiopn to above principles:
Below you can see simple example of Redux action, store,reducer, dispatch:
-
We need store subscribe to follow all store changes. When you doing some dispatch action with store.subscribe you can follow all state changes.
-
In redux you can have only 1 store, 1 single source of truth. In larger app it can become little bit messy. In mobx you can have few stores. You can split yoru state into multiple store, each represeinting different slice of your app logic. Mobx store can also communicate if needed. So for bigger applications Mob'x is more modular and scalable.
-
In short reasons for using reducers are: maintability, performance, scalability.
-
You can use immer library. Example of use: Illustration which shows how immer works:
Reducers in Redux must return a new state object rather than modifying the existing state.State in Redux is not mutable.
-
Yes redux state is immutable. We don't make changes to Redux state, instead of it we're providing new state object whenever there is redux state change.
Immer library helps to work, edit, mutate redux state directly. Below you can find reducer created with immer and without it:
![image](https://github.com/user-attachments/assets/37bd6b95-5a4c-45e0-bb8b-d75ac282e412)
Middleware - is some extendsion between dispatching an action and reaching it to the reducer. Often middleware is used for logging,
cach reporting, performance asynch tasks.
-
Redux thunk - Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met We use redux thunk to fetch some data for example @reduxjs/toolkit includes redux thunk by befault.
-
Redux saga - is a library that aims to make application side effects (i.e. asynchronous things like data fetching and impure things like accessing the browser cache) easier to manage, more efficient to execute, easy to test, and better at handling failures
-
Redux toolkit. Main reason is boilderlating, it's a problem while using redux.
What is cool with redux-toolkit we can directly mutate state. We don't need to copy it as it we should do with normal redux. We just create reducer and mutate here ordererd state directly. What does createSlice:
Redux toolkit createSlice - is reducer version, you define your reducer actions and initial state
-
redux-extrareducer. We need it if for example you have to 2 different reducers, and you need to respond on some action from another reducer. Here in icecreamReducer we respond on cakeOrdered type of action.
-
Imagine your Redux store is like a library, and it has a catalog of books (the state). If you want to find out how many books are in the library, you can use useSelector to "select" and read that specific piece of information.
-
We create style classses with help of react-native api stylesheet. Check next example:
const styles = StyleSheet.create({ container: { backgroundColor: 'green' } });
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
This termin stands for Coordinated Universal Time. An example - New York City is in the UTC-5 time zone, which means the time in NYC is five hours behind UTC.
To run an Express server that serves a React app, the typical approach is to first build the React app into static assets (HTML, CSS, JS), and then use Express to serve those assets.
- So as it can be seen. Middleware it's something between request and response. Middleware is also accessible to change the requests and response objects, and can also terminate the response cycle, if necessary.
- Fs moudule - the built-in Node.js file system module helps us store, access, and manage data
- Main advantage of react-hook-form its performance is very well improved. It stands out for its performance and minimal re-rendering, which is achieved using uncontrolled components. This means that form inputs are not directly managed by the React component state, reducing the re-renders required when users type in data
- headers: { 'Content-Type': 'application/json' } = it will automatically convert your data to json. When you make post request for example
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.
-
*styled components
Difference between simple styling and styled components:
- Automatic critic css - when you page is loaded. Styled components keeps tracking of which components are rendered. ANd injectes only necessary styles.
- No class names bugys - library generates unique clssanames for components. You don't have to worry about dublication, misspeling and similar problems.
- Scoping. Regular CSS files are global by default. You need to be careful with naming conventions and avoid classnamecollisions. Styled components generate unique class names for each component ensuring that styles are always scoped to the component they belong to. Every styled component is scoped by default.
- Dynamic styling - with playin CSS, you can't access JavaScript variables and states to create dynamic states. Styled components allows you to use JS directly in your styles.
- Component based styling. Styles apre placed along with js code of component.
- Theming - with css variables you can create basic theming. Styled components has built-in them suporting using themProvider.
- Performance. Regular css files - style loading is separated from JavaScript, which can be better for performance in certain cases Styled components - Styled components injects styles as javaScript executes. It can be beneficial for dynamic styles but may cause slight performance problems.
-
static - default element position. The element will flow winto the page as it normally would. Relative - the element is positioned relatively to its normal position. It really means 'relative to yourself'. You can use now top. left, bottom. right properties to set position of that element. When you set relative positioning - we can you z-index on that element. Other thing - it limits the scope of absolutely positioned child elements. Any element that is a child ot the relatively positioned elmemnt, can be be absolutely positioned. Absolute - when we want to place any page element exactly where we want it. An element with this type of positioning is not affected by other elements and it dones'nt affect other element. Fixed - positioned realteve to the viewport. The viewport doesn't change when the window is scrolled, so element stays right where it is when the page is scrolled. Sticky - a sticky element will stick like a static elemen until some scrolling position. Then it will behave like fixed element.
Examples of using. How to use props wity styled component: And inside styled: Add color with help of theme: You can add also optional styles like that:
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.