Skip to content

Instantly share code, notes, and snippets.

@threepointone
Last active November 2, 2018 00:41
Show Gist options
  • Save threepointone/c5fd0bab88add4e711912285df2ee117 to your computer and use it in GitHub Desktop.
Save threepointone/c5fd0bab88add4e711912285df2ee117 to your computer and use it in GitHub Desktop.
hooks-arent-functions

the "why do hooks need components to test?" confusion

Hooks look and behave like regular functions. which make expectations around them... weird.

Consider useState. Suppose I tell you, this is its usage -

const [state, setState] = useState(initial)

then this seems like a completely reasonable test to write -

test('it can change values', () => {
  const [state, setState] = useState(0)
  expect(state).toEqual(0)
  setState(20)
  expect(state).toEqual(20)  
})

Except not really, becaue they need to execute in the context of a component to 'actually' work.

This has always been true for HOCs and renderprops as well, except that because the first was a component, and the second needed a render tree to execute, it was obvious that they 'belonged' to a components. But a side effect of successfully peeling off this logic from react's render tree, is that they look and feel like regular functions, hence the expectation. Fascinating.

I think it's only a matter of time before education/expectations/tools catch up to this new reality.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment