--- 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 { // Note: this syntax is experimental and not standardized yet. 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 binding necessary at all? In JavaScript, these two code snippets are **not** equivalent: ```js obj.method(); ``` ```js var method = obj.method; method(); ``` Binding methods helps ensure that the second snippet works the same way as the first one. With React, typically you only need to bind the methods you *pass* to other components. For example, ` } ``` Instead, *pass the function itself* (without parens): ```jsx render() { // Correct: handleClick is 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 ; } handleClick() { this.props.loadMore(); } } ``` #### 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 { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.emitChangeDebounced = debounce(this.emitChange, 250); } componentWillUnmount() { this.emitChangeDebounced.cancel(); } render() { return ( ); } handleChange(e) { // 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.emitChangeDebounced(e.target.value); } emitChange(value) { this.props.onChange(value); } } ``` #### `requestAnimationFrame` throttling [`requestAnimationFrame`](https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame) is a way of queuing a function to be executed in the browser at the optimal time for rendering performance. It is very similar to `setTimeout` except it takes no time argument. A function that is queued with `requestAnimationFrame` will fire in the next frame. The browser will work hard to ensure that there are `60` frames per second (`60 fps`). However, if the browser is unable to it will naturally *limit* the amount of frames in a second. For example, a device might only be able to handle `30 fps` and so you will only get `30` frames in that second. Using `requestAnimationFrame` for throttling is a useful technique in that it prevents you from doing more than `60 updates` in a second. If you are doing `100` updates in a second this creates additional work for the browser that the user will not see anyway. > Using this technique will only capture the last published value in a frame. You can see an example of how this optimization works on [`MDN`](https://developer.mozilla.org/en-US/docs/Web/Events/scroll) ```jsx import rafSchedule from 'raf-schd'; class ScrollListener extends React.Component { constructor(props) { super(props); // keep a record of the id of the next animation frame this.nextFrameId = null; this.handleScroll = this.handleScroll.bind(this); // create a new function that will schedule updates this.scheduleUpdate = rafSchedule(this.emitUpdate.bind(this)); } handleScroll(e) { // When we receive a scroll event, we are going to schedule an update // If we receive many updates within a single frame duration we will // only be publishing the latest value. this.nextFrameId = this.scheduleUpdate({ x: e.clientX, y: e.clientY }); } emitUpdate(point) { this.props.onScroll(point); } componentWillUnmount() { // As we are unmounted we can clear the next animation frame cancelAnimationFrame(this.nextFrameId); } render() { // Creating a scroll container around a big image return (
); } } ``` #### Testing your rate limiting When testing your rate limiting code works correctly it is helpful to have the ability to fast forward time. If you are using [`jest`](https://facebook.github.io/jest/) then you can use [`mock timers`](https://facebook.github.io/jest/docs/en/timer-mocks.html) to fast forward time. If you are using `requestAnimationFrame` throttling then you may find [`raf-stub`](https://github.com/alexreardon/raf-stub) to be a useful tool to control the ticking of animation frames.