1

I am going through the code of a project and I see the following code:

export const FileLink = React.memo(({ url, data, ext, linkContent }) => {
    ...
    ...

  if (!url.includes('?')) {
    url += '?' 
  }
  if (!url.endsWith('?')) {
    url += '&' 
  }
  return <a href={`${url}file_format=${ext}`}>{linkContent}</a>
})

It is working fine and no bugs appear in app behavior. But url is a passed parameter and it is changed within the FileLink: from what I read React components should be pure functions. So, I wonder whether its ok to do that, under which circumstances, and if not - why? What can go wrong? Any examples of how it could mess up the app?

(If interested to see the full code: https://github.com/broadinstitute/seqr/blob/8b4419285dfac9365c5c500bbb87b89808c0cedd/ui/shared/components/buttons/ExportTableButton.jsx#L37)

0

1 Answer 1

1

url is a local variable. Reassigning that variable, which is all this code is doing to it, has no possibility of affecting code outside of this function call. It doesn't make the function impure.

Now, if you were passed in an object, and you started mutating that object, then that would break purity. Because if the component that passed you this object is still using it, then it can "see" that change. For example:

const Example = ({ someObjectProp }) => {
  someObjectProp.name = 'bob';
}
Sign up to request clarification or add additional context in comments.

2 Comments

but url is passed in or it becomes local because it is a string and upon passing it into FileLink it is copied?
({ url, data, ext, linkContent }) => This code is a destructuring assignment. It's the same as (props) => { let url = props.url // etc. url is a local variable that starts off with the same value as props.url. Reassigning this variable later doesn't have any effect outside the function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.