Published on

React Using Stateless Functional Components Instead of Classes

Authors

In React there are 2 ways of writing a component:

  1. As a class
  2. As a function

I used the functional approach today and found it to be much cleaner and more succinct. Other proponents of this second approach argue how it also leads to less errors as there is no confusion about this. You can also destructure attributes as inputs to the function which can be more readable.

To define a functional component you would do it as follows:

const MyAwesomeComponent = ({ prop1, prop2 }) => {
  return <div>...</div>
}

export default MyAwesomeComponent

You would use this as normal <MyAwesomeComponent prop1="foo" prop2="bar"/>. One thing that is not immediately obvious with this approach is how you would hook into lifecycle methods and use state. After a bit of Googling I discovered that there is an opt-in alpha feature in React v16.7.0-alpha called hooks which addresses exactly this issue.

Using the functional component approach you can even modify the main App component. Normally you have something like:

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <p>
            Edit <code>src/App.js</code> and save to reload.
          </p>
          <a
            className="App-link"
            href="https://reactjs.org"
            target="_blank"
            rel="noopener noreferrer"
          >
            Learn React
          </a>
        </header>
      </div>
    )
  }
}

export default App

Using the functional approach you can instead make it more concise like this:

const App = () => {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  )
}

export default App