liveBook · Manning

Pure function

As explained in React Quickly, Second Edition

A pure function is a function whose result depends only on its arguments and that has no observable side effects.

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

How React Quickly, Second Edition covers it

How deep it goes
Defines argument dependence and side-effect freedom, then works through React conversion trade-offs without examining implementation internals.
Examples
Demonstrates image-source generation in a gallery and compares external utilities with methods reading component properties.
What it assumes
Starts with ordinary functions and React components, while teaching purity through props, arguments, and side effects.
What you can do after
Apply it by extracting React utilities, passing required properties explicitly, and identifying when a local function is simpler.
How it connects
Connects pure functions with functional components, class methods, utility functions, hooks, unit testing, and reducers.

Also explained in

Compare how 19 books explain pure function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of React Quickly, Second Edition. The section links point to the parts of the book it draws on.