Migrate from recompose withState to React Hooks useState

Migrate from recompose withState to React Hooks useState

ยท

4 min read

So, you used to use recompose in your React app to add state to your stateless functional components, before the Hooks API was launched.

The time has come to upgrade to React 16 and make use of the new way of managing state within your functional components (note that they're now no longer stateless).

This guide will walk through a simple example of migrating your state over to Hooks.

Before, using recompose

Here's a simple example of a Counter using recompose, which has the following components

  • One piece of state using withState
  • One event handler using withHandlers

After, using hooks

Here's how our Counter component looks after converting it to use the Hooks API. Notice the following:

  • We make use of the useState hook
  • Our event handler incrementCounter is now a const within our Counter component

Solution Explained

The useState hooks lets us add React state to our functional component. There is no longer a requirement to use a class or to use a library like recompose to provide state to your functional components.

Instead of calling our setCounter state mutator function directly within our presentation code, we have created an event handler called incrementCounter which we can then pass to our onClick which allows us to keep our logic separated from our presentational code.

Rules of Hooks

There are some special rules that must be followed to make sure that your Hooks work.

  • Hooks should only be called from React function components or from custom hooks.
  • Hooks should not be called within loops, conditions or nested functions, instead you should use your hooks at the top level of your functions.
// BAD Example - Hook used within a condition
const Counter = ({ useCounter }) => {
    if (useCounter) {
        const [counter, setCounter] = useState(0);
    }

    return (
        <div>
            // Presentational code here
        </div>
    )
}

// Better Example - Hook used at top level of function
const Counter = () => {
    const [counter, setCounter] = useState(0);

    return (
        <div>
            // Presentational code here
        </div>
    )
}

This is a very basic guide on how to get running with a simple state hook.

Thank you for taking the time to read this blog post. I learn better when writing stuff down, which is why I have transformed my notes into this blog article so that the community can benefit also. Keep bloggin' โœŒ๏ธ - Naz