A pure function returns a result using only its arguments. It does not depend on outside information or produce observable side effects, so its behavior is easier to understand and test. section 4.4.2 section 4.2.1
When converting React class code, use purity as a practical design choice:
- Move a utility outside the component when it needs only explicit arguments. section 4.4.2
- Replace access to component properties with arguments, such as width, height, and index. section 4.4.3
- Keep a local function when passing every required property would make the call unnecessarily complex. section 4.4.3
Generating an image URL
function getImageSource(index) {\n return `//picsum.photos/id/${index}/150/150/`;\n}\n\nfunction Image({ index, title }) {\n return (\n <figure>\n <img src={getImageSource(index)} alt={title} />\n <figcaption>Species: {title}</figcaption>\n </figure>\n );\n}\n\ngetImageSource depends only on index, so it can live outside Image. A class method that reads this.props instead relies on outside component information and is not directly equivalent. section 4.4.2 section 4.4.3
Listing 4.13 Gallery v2 using functions (excerpt)
...
function getImageSource(index) { #1
return `//picsum.photos/200/100/animals/${index}/`;
}
function Image({ index, title }) {
return (
<figure style={{ margin: "5px" }}>
<img src={getImageSource(index)} alt={title} /> #2
<figcaption>
Species: {title}
</figcaption>
</figure>
);
}
...
Browse a complete functional gallery excerpt showing a pure URL utility called with component props. section 4.4.2


















