--- id: faq-functions title: Passing Functions to Components permalink: docs/faq-functions.html layout: docs category: FAQ --- ### How do I pass an event handler (like onClick) to a component? Pass event handlers and other functions as props to child components: ```jsx } } ``` #### Class Properties (Stage 3 Proposal) ```jsx class Foo extends Component { handleClick = () => { console.log('Click happened') } render() { return } } ``` #### Bind in Render ```jsx class Foo extends Component { handleClick () { console.log('Click happened') } render() { return } } ``` >**Note:** > >Using `Function.prototype.bind` in render creates a new function each time the component renders, which may have performance implications; (see below). #### Arrow Function in Render ```jsx class Foo extends Component { handleClick () { console.log('Click happened') } render() { return } } ``` >**Note:** > >Using an arrow function in render creates a new function each time the component renders, which may have performance implications; (see below). ### Is it OK to use arrow functions in render methods? Generally speaking, yes, it is OK, and it is often the easiest way to pass parameters to callback functions. If you do have performance issues, by all means, optimize! ### Why is my function being called every time the component renders? Make sure you aren't _calling the function_ when you pass it to the component: ```jsx render() { {/* handleClick is called instead of passed as a reference! */} return } ``` ### How do I pass a parameter to an event handler or callback? You can use an arrow function to wrap around an event handler and pass parameters: ```jsx this.handleClick(id)} /> ``` This is equivalent to calling `.bind`: ```jsx ``` #### Example: Passing params using arrow functions ```jsx const A = 65 // ASCII character code class Alphabet extends React.Component { state = { justClicked: null, letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i)) } handleClick = letter => this.setState({ justClicked: letter }) render () { return (
Just clicked: {this.state.justClicked}
    { this.state.letters.map(letter =>
  • this.handleClick(letter)}> {letter}
  • ) }
) } } ``` #### Example: Passing params using data-attributes Alternately, you can use DOM APIs to store data needed for event handlers. Consider this approach if you need to optimize a large number of elements or have a render tree that relies on React.PureComponent equality checks. ```jsx const A = 65 // ASCII character code class Alphabet extends React.Component { state = { justClicked: null, letters: Array.from({length: 26}, (_, i) => String.fromCharCode(A + i)) } handleClick = event => { this.setState({ justClicked: event.target.dataset.letter }) } render () { return (
Just clicked: {this.state.justClicked}
    { this.state.letters.map(letter =>
  • {letter}
  • ) }
) } } ``` ### How can I prevent a function from being called too quickly or too many times in a row? If you have an event handler such as `onClick` or `onScroll` and want to prevent the callback from being fired too quickly, you can wrap the handler with a utility such as [`_.debounce`](https://lodash.com/docs#debounce) or [`_.throttle`](https://lodash.com/docs#throttle). See [this visualization](http://demo.nimius.net/debounce_throttle/) for a comparison of the two. > Note: > > Both `_.debounce` and `_.throttle` provide a `cancel` method to cancel delayed callbacks. You should either call this method from `componentWillUnmount` _or_ check to ensure that the component is still mounted within the delayed function. #### Throttle Throttling prevents a function from being called more than once in a given window of time. The example below throttles a "click" handler to prevent calling it more than once per second. ```jsx import throttle from "lodash.throttle"; class LoadMoreButton extends React.Component { componentWillUnmount() { this._handleClick.cancel(); } render() { return ; } _handleClick = throttle(() => { this.props.loadMore(); }, 1000); } ``` #### Debounce Debouncing ensures that a function will not be executed until after a certain amount of time has passed since it was last called. This can be useful when you have to perform some expensive calculation in response to an event that might dispatch rapidly (eg scroll or keyboard events). The example below debounces text input with a 250ms delay. ```jsx import debounce from "lodash.debounce"; class Searchbox extends React.Component { componentWillUnmount() { this._handleChangeDebounced.cancel(); } render() { return ( ); } _handleChange = event => { // React pools events, so we read the value before debounce. // Alternately we could call `event.persist()` and pass the entire event. // For more info see reactjs.org/docs/events.html#event-pooling this._handleChangeDebounced(event.target.value); }; _handleChangeDebounced = debounce(value => { this.props.onChange(value); }, 250); } ```