One of the recent additions to React was its hooks. With that, developers don’t need to rely on libraries such as Recompose to add state (and other features) to functional components.

If you’re one of those devs and were used to create custom setters for states, it’s possible you find the new useState hook somewhat limited. But you still can write your own setters, wrapping the setter returned by useState into another function.

Consider the following Recompose code:

withStateHandlers({
    counter: 0,
}, {
    increment: ({ counter }) => {
        return () => ({
            counter: counter + 1,
        });
    },
    decrement: ({ counter }) => {
        return () => ({
            counter: counter - 1,
        });
    },
});

You may write the same logic with React hooks this way:

const [ counter, setCounter ] = useState(0);
const increment = () => {
    setCounter(counter + 1);
};
const decrement = () => {
    setCounter(counter - 1);
};

This probably seems pretty obvious but there are some cases where you may need to apply some side-effect to your setter and this approach would be useful. Here it goes an example, given the same state above:

const [ counter, _setCounter ] = useState(0);
const setCounter = (counter) => {
    // Some side-effect here ...
    _setCounter(counter);
    // ... or there
};

For questions and suggestions, please leave a comment below.

Advertisements

Leave a comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.