- React Design Patterns and Best Practices(Second Edition)
- Carlos Santana Roldán
- 236字
- 2021-06-24 15:43:42
Purity
An important aspect of FP is to write pure functions. You will encounter this concept very often in the React ecosystem, especially if you look into libraries such as Redux.
What does it mean for a function to be pure?
A function is pure when there are no side-effects, which means that the function does not change anything that is not local to the functions itself.
For example, a function that changes the state of an application, or modifies variables defined in the upper scope, or a function that touches external entities, such as the DOM, is considered impure. Impure functions are harder to debug, and most of the time it is not possible to apply them multiple times and expect to get the same result.
For example, the following function is pure:
const add = (x, y) => x + y;
It can be run multiple times, always getting the same result, because nothing is stored anywhere and nothing gets modified.
The following function is not pure:
let x = 0;
const add = y => (x = x + y);
Running add(1) twice, we get two different results. The first time we get 1, but the second time we get 2, even if we call the same function with the same parameter. The reason we get that behavior is that the global state gets modified after every execution.
- Mastering Node.js(Second Edition)
- Spring Boot 2.0 Projects
- 物聯(lián)網(wǎng)+BIM:構(gòu)建數(shù)字孿生的未來
- 互聯(lián)網(wǎng)基礎(chǔ)資源技術(shù)與應(yīng)用發(fā)展態(tài)勢(2021—2023)
- 計算機(jī)網(wǎng)絡(luò)工程實用教程(第2版)
- Socket.IO Real-time Web Application Development
- Microservice Patterns and Best Practices
- 計算機(jī)網(wǎng)絡(luò)技術(shù)及應(yīng)用
- 大型企業(yè)微服務(wù)架構(gòu)實踐與運營
- 基于IPv6的家居物聯(lián)網(wǎng)開發(fā)與應(yīng)用技術(shù)
- Selenium WebDriver 3 Practical Guide
- 物聯(lián)網(wǎng)與智慧農(nóng)業(yè)
- 移動互聯(lián)網(wǎng)環(huán)境下的核心網(wǎng)剖析及演進(jìn)
- 從物聯(lián)到萬聯(lián):Node.js與樹莓派萬維物聯(lián)網(wǎng)構(gòu)建實戰(zhàn)
- 智能物聯(lián)網(wǎng):區(qū)塊鏈與霧計算融合應(yīng)用詳解