React Concept: Purity

By

Published · Updated

Tagged: React

Understand purity in React: a pure function returns the same output for the same input with no side effects, and a pure component depends only on its props.

In JavaScript, when a function does not mutate objects but just returns a new object, it’s called a pure function.

A function, or a method, in order to be called pure should not cause side effects and should return the same output when called multiple times with the same input.

A pure function takes an input and returns an output without changing the input nor anything else.

Its output is only determined by the arguments. You could call this function 1M times, and given the same set of arguments, the output will always be the same.

React applies this concept to components. A React component is a pure component when its output is only dependent on its props.

React expects every component to be pure while it renders: same props, state and context in, same JSX out, with no side effects during rendering. Side effects go in event handlers or in useEffect.

A function component that only reads its props is pure:

const Button = props => {
  return <button>{props.message}</button>
}

Class components can be pure if their output only depends on the props:

class Button extends React.Component {
  render() {
    return <button>{this.props.message}</button>
  }
}

What makes a component impure

The most common mistake is changing a variable that lives outside the component while rendering:

let guest = 0

function Cup() {
  guest = guest + 1 // 🚩 changes a variable that existed before
  return <h2>Tea cup for guest #{guest}</h2>
}

export default function TeaSet() {
  return (
    <>
      <Cup />
      <Cup />
      <Cup />
    </>
  )
}

Every time React renders Cup, the output is different, even with the same props. If React renders it again for any reason, the numbers change.

The fix is to pass the value in as a prop:

function Cup({ guest }) {
  return <h2>Tea cup for guest #{guest}</h2>
}

export default function TeaSet() {
  return (
    <>
      <Cup guest={1} />
      <Cup guest={2} />
      <Cup guest={3} />
    </>
  )
}

Other things that make rendering impure:

Changing local variables is fine

Purity is about things that existed before the component was called. You can create an array during render and push into it as much as you want, because no other code can see it:

export default function TeaGathering() {
  const cups = []
  for (let i = 1; i <= 12; i++) {
    cups.push(<Cup key={i} guest={i} />)
  }
  return cups
}

Strict Mode finds impure components for you

In development, when your app is wrapped in <StrictMode>, React calls each component function twice. A pure component gives the same result both times, so you don’t notice anything.

The impure Cup above shows guest #2, #4 and #6 instead of #1, #2 and #3. That’s the hint something is wrong. In production React calls it once. See React StrictMode for how to turn it on.

Where side effects go

Your app still needs to do things: save data, call APIs, start animations. You do them outside of rendering.

  1. In event handlers, like onClick or onSubmit. They run when the user does something, not during render, so they don’t need to be pure. This is the first place to look.
  2. In useEffect, when there’s no event to attach it to, for example to connect to a server when a component appears on screen. React runs it after rendering.

Why React cares

React relies on purity to do its job:

Don’t confuse pure components with React.PureComponent. That’s a class you can extend so a class component skips re-rendering when its props and state are shallowly equal to the previous ones. Every component should be pure, whether or not it uses PureComponent or memo.

Want me to talk about your product? You can sponsor this site.

Related posts about react: