Skip to main content

Command Palette

Search for a command to run...

it's Necessary To Use .bind(null, x) in React ?

Updated
2 min readView as Markdown
it's Necessary To Use .bind(null, x) in React ?

The bind method allows us to pre-configure a function.

It does not execute the function right away. Instead it's a default JavaScript method, which you can use on any function object to pre-configure that function. The first argument you pass to bind then allows you to set the this keyword in the to-be-executed function, which does not matter to us here. Hence, we can set this to null. But the second argument you pass to bind will then be the first argument received by that to-be-called function.

Note: By using .bind(null, item.id), a new function will be created each time the component renders

Note: Using an arrow function in render creates a new function each time the component renders, which may break optimizations based on strict identity comparison.

Example:

<CartItem onRemove={cartItemRemoveHandler.bind(null, item.id)} />

We can't just write ...

onRemove = { cartItemRemoveHandler(item.id) }

Since this would call the function immediately (and not when the cart item is clicked).

So, if we want to pass params, we can either use bind (the first param is not used here, so we can write anything in this place)

onRemove = { cartItemRemoveHandler.bind(null, item.id)}

Or we can create an anonymous function:

onRemove={ ( ) => cartItemRemoveHandler(item.id) }

Both options are equivalent

=================================

This line ...

createTask.bind(null, taskText)

... is equivalent to this anonymous function, which might be easier to understand:

(taskData) => createTask(taskText, taskData)

The bind syntax might look strange, but it's defined in the way how Max explains it.

=======================================

btn.addEventListener('click', (event) => doSomething1(event, 42));
btn.addEventListener('click', doSomething2.bind(null, 42));  

function doSomething1(arg1, arg2) {
  console.log(arg1, arg2);                            // MouseEvent {...}, 42
}

function doSomething2(arg1, arg2) {
  console.log(arg1, arg2);                            // 42, MouseEvent {...}
}

More from this blog

Omar's blog

135 posts