본문 바로가기

JavaScript8

[JavaScript] 마이크로 태스크(Micro Task)와 매크로 태스크(Macro Task) 03.24.2024 0. Background 요즘 코딩 컨텐츠 검수 아르바이트를 하는 중인데 그 곳에서 알게된 개발자님이 컨텐츠 중 한 문제를 보내주셔서 풀어본 문제를 정리해보려 한다. 1. 코드 function a() { console.log('a1'); b(); console.log('a2'); } function b() { console.log('b1'); c(); console.log('b2'); } async function c() { console.log('c1'); setTimeout(() => console.log('setTimeout'), 0); await d(); console.log('c2'); } function d() { return new Promise(resolve => { c.. 2024. 3. 25.
[JS] Swap in JavaScript 01.04.2023 1. Temporary Variable Temp 변수를 이용하여 Swap 구현 let a = 1; let b = 2; let temp; temp = a; a = b; b = temp; console.log(a); // => 2 console.log(b); // => 1 2. Destructuring assignment (구조 분해 할당) 원래 하던 Swap에서 동등 연산자를 기준으로 괄호를 추가해주면 된다. let a = 1; let b = 2; [a, b] = [b, a]; console.log(a); // => 2 console.log(b); // => 1 꼭 양 변의 갯수가 맞지 않더라도 동작은 한다. 그러나 이 경우 주의해야 할 점이 있는데, 왼쪽항의 변수 갯수가 오른쪽 항의 .. 2024. 1. 4.
메모이제이션이란?(useMemo, useCallback) in React.js 06.26.2023 1. 메모이제이션의 정의 같은 함수가 같은 값을 계속 리턴해야할 때, 첫 번째 값을 메모리에 저장해놓고 메모리에서 값을 불러와 재사용하는 메모리 사용 기법. 2. 활용도 2-1. useMemo 예를 들어 이러한 함수형 컴포넌트가 있다고 하자. function Component () { const result = calculate(); return {result} } function calculate () { // 무거운 작업을 하는 코드 return 10; } 이 컴포넌트가 렌더링이 될 때마다 calculate은 무거운 작업을 계속해야 할 것이다. 그러나 result는 항상 10일 때, 성능이 비효율적이 될 것. 이럴 때 메모이제이션을 사용하여 해결 가능 function Compone.. 2023. 6. 26.
5. Query Callback (쿼리콜백) in Node.js 0. Problem app.post('/api/rate', (req,res) => { const {residentName, quality, diff, willing, comment, tags} = req.body; let id = 0; db.query(`SELECT id FROM resident WHERE name = ?;`, [residentName],(err,result)=>{ if(err) throw err; console.log(result); id = result[0].id; }); const query = `INSERT INTO rate(resident_id, quality_rate, difficulty_rate, willingness, comment${tagQueryFront} VALUES .. 2023. 4. 11.
4. Using Variables in useEffect (useEffect에서 변수 쓰기) 03.16.2023 0. Background What I wanted to do was to use the prop as name for components and fetching data from database when props was passed in the result page from the main page. Here is what I did. 1. Store the prop as name using useState function Result(props){ const [name, setName] = useState(null); // Set name using useEffect useEffect(()=>{ if(location.state === null) setName(props.name);.. 2023. 3. 16.
3. Spread Operator (Managing Array State) 2023.03.02 0. Background The reason that made me search for and use it is basically that I wanted to manage a state of an array through useState hook. It didn't work when I tried just updating the array with array functions like this: import {useState} from 'react'; const [tags, setTags] = useState([]); const setTags = (tag) => { setTags(tags.push(tag)); }; const removeTags = () => { setTags(tag.. 2023. 3. 2.