7

I was wondering what people suggest when working with optional default functions in React.

I have seen our codebase use a mix of () => {} and the lodash noop.

Which is preferable?

This is a general question regarding proper coding techniques.

export default ({
  name = '',
  value = '',
  label = name,
  type = 'text',
  noLabel = false,
  placeholder = '',
  required = false,
  isInvalid = false,
  showBar = true,
  inputRef,
  onChange = () => {},
  onBlurCb, // <-- THE BIT IN QUESTION
  ...props
}) => (
  <Component initialState={{ isFocused: false, hasValue: false }}>
    {({ state, setState }) => (
      <InputContainer
        isFocused={state.isFocused}
        isInvalid={isInvalid}
        noLabel={noLabel}
        {...props}
      >
...

This is used as a callback to a synthetic event later down in a component

onBlur={() => {
            setState({ isFocused: false })
            onBlurCb()
          }}
ParthianShotgun
  • 602
  • 4
  • 20
  • There is no practical difference, so this comes down to readability preference. They are both pretty clear ways of showing `noop`. – Ryan Cogswell Jan 21 '19 at 19:57
  • 1
    `() => {}` should be pretty clear that it does nothing (assuming you're familiar with the syntax) but whether it's clear that it's *supposed* to be a noop or not may not be. It depends on the reader and/or context. An explicitly named `noop` would be clear that you've *put* something there but it's *not* supposed to do anything, as opposed to having an unfinished function (perhaps you wrote `() => {}`, meant to put some code in but somebody phoned you). Still, it would all be opinion based for which is "best". – VLAZ Jan 21 '19 at 20:02

1 Answers1

13

This is the source code of _.noop():

function noop() {
  // No operation performed.
}

As you can see it's identical to () => {}.

The main downside to _.noop() is the need to import it (another line of code).

Except for that, you should use the convention in your team, or if none - the one that is more readable to you.

As a personal preference I would skip the import, and go with () => {}.

Ori Drori
  • 183,571
  • 29
  • 224
  • 209