Introduction to Closures with React

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). If you are having trouble understanding what Closures are or…

Chances are, you’ve been using Closures for a long time without even realizing it. A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). If you are having trouble understanding what Closures are or how they’re used, this article will give an introduction to both. I’ll be showing a very simple example of a Closure in a React component. My goal is to provide an easy introduction to what Closures are, how they work, and where you are most likely to use them. Simple Closure Example:

import { IRootState } from "@app/typings";
import * as React from "react";
import { useSelector } from "react-redux";

const PostUrlList: React.FunctionComponent = (props) => {
  const { posts, uid } = useSelector((state: IRootState) => state.account);

  const getPostUrl = (post: IPost) => {
    const availabilityPrefix = post.private
      ? "myprivateposturl"
      : "mypublicposturl";
    return `https://${availabilityPrefix}/post.id?uid=${uid}`;
  };

  return (
    <div>
      {posts.map((post) => (
        <a key={post.id} href={getPostUrl(post)}></a>
      ))}
    </div>
  );
};

export default PostUrlList;

In the example above, we are using a function to create a URL for each post in a list. The function uses parameters passed to it, as well as a uid variable declared in an outer function. I use this pattern all the time in React projects I work on. Global state variables are commonly referenced when discussing Closures. Every function we declare has the potential to become a Closure. Closures occur when a function references variables outside of its immediate scope. They accomplish this by bundling references to outer variables with the rest of the function body when the function is created. When talking about Closures, the area outside of a function is referred to as the Lexical Environment. With that in mind, the getPostUrl function is an example of a Closure because it references the uid variable in our lexical environment. The outer variables you reference don’t have to belong to a global state object to make a Closure.

import { IRootState } from "@app/typings";
import * as React from "react";
import { useSelector } from "react-redux";
import { myHelperFunc } from "./helpers";

const PostUrlList: React.FunctionComponent = (props) => {
  const { posts, uid } = useSelector((state: IRootState) => state.account);

  const getPostUrl = (post: IPost) => {
    const helper = myHelperFunc();
    const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;

    const availabilityPrefix = post.private
      ? "myprivateposturl"
      : "mypublicposturl";
    return `https://${availabilityPrefix}/post.id?uid=${uid}`;
  };

  return (
    <div>
      {posts.map((post) => (
        <a key={post.id} href={getPostUrl(post)}></a>
      ))}
    </div>
  );
};

export default PostUrlList;

If you were to reference either the myHelperFunc function or the Intl API you would also be creating a Closure.

Enjoyed this article?

Share it with your network to help others discover it

Continue Learning

Discover more articles on similar topics