React UI Elements as Pure Functions

Jul 31, 2017

Functional programming -- which has been around over 50 years, way longer than Object Oriented programming! -- enables brevity, concurrency, testability, and simplicity.

Most programmers do not have the luxury to write in functional languages (such as Clojure, Elixir or Haskell) every day, but there are many lessons to be learned that can be applied to all code. One example, programming React UI components in a functional style, will improve your code, and help you write really clean tests.


 Let’s talk about writing React components as pure functions.

Quick Review of Pure Functions

Pure function example

A pure function is a function which, given the same input, will always return the same output. An example: When 10 and 20 are the inputs, the function will always return the same output, 30.

function sum(x,y) {
   return x + y ;
}
sum(10, 20) // returns 30
sum(10, 20) // returns 30
sum(10, 20) // returns 30

Testing Pure Functions

Because there are such clear inputs and outputs, unit testing pure functions is easy. We test what goes in, and what comes out -- that’s it.

describe("sum", () => {
   it("returns the sum of 10 and 20.", () => {
      expect(sum(10, 20)).toEqual(30)
   })
})

Impure Function Example

Contrast this to an impure function. Notice the side-effect that the value of count changes each time the function is invoked.

var count = 10;
function increaseCount(value) {
   count += value;
}
increaseCount(10) // count is now 20
increaseCount(10) // count is now 30
increaseCount(10) // count is now 40

increaseCount’s return value is dependent on an outside variable -- count -- which could potentially be hard to track down and replicate in a test. As codebases get larger and more complex, and more developers join a team, this type of code will lead to bugs and will be harder to understand. Better to rely on the simplicity of a Pure Function, in which the output is totally based on the input.

Stateless Functional React Components as Pure Functions

The React API, along with jsx, provides a simple way in which you can create simple HTML UI elements that behave like pure functions. Here is a very simple example from the React documentation-- invoking the Welcome function, given the same input, will always render the same output html.

function Welcome({ name }) {
   return <h1>Hello, {name}</h1>;
}
<Welcome name="Keir" /> // <h1>Hello, Keir</h1>
<Welcome name="Keir" /> // <h1>Hello, Keir</h1>
<Welcome name="Keir" /> // <h1>Hello, Keir</h1>

And is just as testable as testing any pure function, using enzyme.

import {render} from 'enzyme';

describe('Welcome', () => {
   it('should render Hello, Keir', () => {
      const wrapper = render(<Welcome name="Keir" />);
      expect(wrapper.contains(‘Hello, Keir’)).toEqual(true);
   });
});

Conclusion

Welcome is a presentational component that is especially conducive to being implemented as a pure function. It takes one argument, a string, and outputs corresponding html. All UI logic can be abstracted into testable and understandable components such as this.

Of course State management is part of every app, and React Class components can be used to manage state. Tools such as Redux and MobX enable a developer to maintain a functional mindset when creating and testing the behavior of an app. Use them! And make sure your UI elements are pure functions.


Want to learn new tactics to help you be a more effective developer? Check out our Tips all Developers Should Know to help you advance your career.

 

You May Also Like

These Stories On Technology

Josh Seiden, the fourth speaker in Stride's Leadership through adversity speaker series, spoke about the value of focusing on outcomes, defined as: "measurable changes in behavior that drive business results."   read more

To start his talk, psychiatrist and psychoanalyst Dr. Kerry Sulkowicz admitted to being at a bit of a loss when asked about best practices for leading through a pandemic. "The honest answer is I don't know," he stated, "because none of us has lived ... read more

Taking direct aim at the narrative of the "all in" entrepreneur who takes extreme risks and depletes their bank account before ultimately succeeding, noted NYC VC Charlie O'Donnell started his Stride Consulting “Leading through Adversity” talk on May ... read more

In response to these unprecedented times and the challenges that they are bringing to company leaders, Stride Consulting launched a speaker series entitled “Leading through Adversity” on May 26th. In the series, experts from around the globe, from a ... read more

Get Email Updates