-
15.순수함수. 불변성과 사이드이펙트 16. 리액트의 state와 props항해99 2023. 4. 5. 14:27728x90
Q. 순수함수란 무엇인가요? 불변성과 사이드 이펙트와 연결하여설명해주세요.
순수함수
부수효과 없는 함수. 즉, 어떤 함수에 동일한 인자를 주었을 때 항상 같은 값을 리턴하는 함수
외부 상태를 변경하지 않는 함수순수함수와 순수함수가 아닌 것
function add(a,b){ return a+b; } console.log(add(19,6))
언제 어디서 add함수를 실행해도 add(19,6)은 항상 25를 리턴하고 외부상태를 변경하지 않았기 때문에
add는 순수하다.let c=10; function add2(a+b){ return a+b+c } console.log(add2(10,3)) c=20; console.log(add2(10,3))
add2는 c라는 변수값이 변하면 결과값도 달라지기 때문에 순수함수가 아니다.
let c=20; function add3(a,b){ c=b; // c를b로 바꿔치기. 외부상태에 영향을 미치는 부수효과를 가져온다. return a+b }
add3은 순수함수가 아니다. 함수가 외부의 값을 변경하는 코드를 갖고있기 때문. 리턴값이 항상 일정해도 외부의 상태를 변경하는 코드가 있다면 순수함수가 아니다.
let obj1={val:1}; function add4(obj,b){ obj.val += b; }
add4는 객체를 인자로 받아서 그 상태를 변경시키는 코드를 가지고 있기 때문에 순수함수가 아니다.
let obj1={val: 10}; function add5(obj, b){ return {val: obj.val + 5}. //obj의 val만 참조할 뿐 변경 없음. }
객체의 값을 참조만 하기 때문에 add5는 순수함수이다.
순수함수란, 함수가 외부에 영향을 미치지 않고 인자로 전달된 값에만 의존하여 값을 계산하고 반환하는 함수입니다. 동일한 인자 값에 대해 항상 같은 결과를 반환하며, 함수 외부의 상태를 변경하지 않습니다. 순수함수와 불변성은 밀접한 관련이 있습니다. 불변성이란, 객체의 상태를 변경할 수 없는 속성을 가지는 객체를 말합니다. 이러한 객체는 생성 이후 변경할 수 없으므로 객체를 참조하는 다른 부분에서 예기치 않은 변경이 일어나지 않습니다. 따라서 순수함수에서는 인자로 전달된 객체를 변경하지 않고, 새로운 객체를 생성하여 반환하는 방식을 사용합니다. 또한 순수함수는 함수 외부의 상태를 변경하지 않아 사이드이팩트가 없습니다. 사이드이팩트란, 함수가 반환하는 값 이외에 함수 외부에 영향을 미치는 작업을 말합니다. 이러한 사이드이팩트를 없애기 위해서 함수 내부에서 외부 상태를 변경하는 작업을 하면 안됩니다. 즉, 함수 내부에서는 입력값만을 사용하여 계산하고, 결과값을 반환하는 방식을 사용해야 합니다. 이렇게함으로써 함수의 결과를 예측 가능하고 안정적으로 만들 수 있습니다
Q. React의 state와 props에 대해서 설명해주세요.
React의 state는 컴포넌트 내에서 관리되는 데이터를 의마합니다. state는 컴포넌트가 랜더링될 때 변할 수 있는 값으로, 사용자의 입력, 또는 네트워크 요청등의 이벤트에 따라 업데이트 됩니다. props는 부모컴포넌트에서 자식컴포넌트로 전달되는 데이터를 의미합니다. props는 읽기 전용으로, 자식 컴포넌트에서는 props를 변경할 수 없습니다. props는 컴포넌트의 인자로 전달되어 해당 컴포넌트는 props에 의존하여 렌더링됩니다.
state와 props의 가장 큰 차이점은 데이터의 변경 가능성입니다. state는 컴포넌트 내에서 변경될 수 있으며, 해당 컴포넌트의 라이프사이클 메소드에서 접근할 수 있습니다. 반면에, props는 읽기 전용으로 해당 컴포넌트에서 변경할 수 없으며, 전달된 값만 사용할 수 있습니다.
728x90'항해99' 카테고리의 다른 글
17. Semantic HTML의 필요성, 18. Redux 주요개념들과 연결관계, 다른 상태관리도구와의 비교 (0) 2023.04.07 13. useRef가 필요한 상황, 14.cookie의 MaxAge, expires옵션 (0) 2023.04.04 11. import&require차이점, 12. const선언시 배열과객체의 요소나 속성을 추가할 수 있는 이유 (0) 2023.04.03 9. this의 동작원리, 용법 10.브라우저 저장소간의 차이점 (0) 2023.04.02 면접대비 7. HTTP메세지구조 8. CSS position속성 (0) 2023.03.30