React Function Components

Are the hot new awesomeness around town, here are a few things I've learned about them that weren't immediately clear by reading the documentation.

Local functions

When creating functions locally (within your component, likely for event handlers) you should use useCallback to ensure that each time something changes in the component it doesn't pass a new reference of the function into the handler property. You can think of this as the equivalent to the class method in a class component.

So this

import * as React from 'react'

const MyComponent: React.FC = props => {

  function myHandlerFunc () {    // do the things!
  }

  return (
    <button onClick={myHandlerFunc}></button>
  )
}

becomes this

import * as React from 'react'

const MyComponent: React.FC = props => {

  const myHandlerFunc = React.useCallback(() => {    // do the things!
  }, [])

  return (
    <button onClick={myHandlerFunc}></button>
  )
}

Content properties

  • Type: Note
  • Category: JavaScript
  • Tags: frontend, javascript, typescript, react
  • Custom slug: None

This is a preview of a simpler page design that I'm working on over the next little bit. I've finally added a (click it!) but there's still a few pages left to be converted so don't worry if things don't look quite right just yet 🙏

Content on blog pages use the CC-BY-SA license. The source code and notes use the MIT license. Unsure? Mention me on Mastodon.