Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?

Use of closures in React

How to make use of closures in React when handling events, to get some performance gains

Example 1

When we don't need the event, neither any parameter to be passed.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  example1 = () => {
    // Here we don't need the event, neither any parameter to be passed
    console.log("Example 1");
    // Do your thing here
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.example1}>Example 1</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Example 2

When we don't need the event, but we need a parameter to be passed.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  example2 = parameter => () => {
    // Here we don't need the event, but we need the parameter to be passed
    console.log("Example 2", parameter);
    // Do your thing here
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.example2("parameter")}>Example 2</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Example 3

When we need the event, but we don't need the parameter to be passed.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  example3 = event => {
    // Here we need the event, but we don't need the parameter to be passed
    console.log("Example 3", event.target);
    // Do your thing here
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.example3}>Example 3</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Example 4

When we need the event, and also the parameter to be passed.

import React, { Component } from "react";
import ReactDOM from "react-dom";

class App extends Component {
  example4 = parameter => event => {
    // Here we need the event, and we also need the parameter to be passed
    console.log("Example 4", parameter, event.target);
    // Do your thing here
  };

  render() {
    return (
      <div className="App">
        <button onClick={this.example4("parameter")}>Example 4</button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Example

Edit HOCs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment