DEV Community

Discussion on: Synchronous State With React Hooks

Collapse
 
havespacesuit profile image
Eric Sundquist

I think you missed Standard (Poor) Solution #7: useCallback

const validateMemberId = useCallback(() => {
    // validate based on the CURRENT value of 'memberId'
    // this function gets updated whenever memberId is updated,
    // so we know it will be the most recent id you just set
    return validOrNot;
}, [memberId]);
Enter fullscreen mode Exit fullscreen mode

It has downsides because now you need to wrap validateForm, updateMemberId and on up through the call chain with useCallback as well. If you have the react-hooks lint plugin installed, it will warn you to do this; otherwise these functions can be re-created with each render.

I've been looking into Recoil lately for situations like this, but I haven't started testing it out yet so I don't have any good thoughts on if it is applicable. Seems a lot simpler than Redux, though!

Collapse
 
bytebodger profile image
Adam Nathaniel Davis • Edited

Great feedback! I've only read about useCallback(). Haven't yet found a great time/place to use it. But you're right, this is definitely another one of the valid options.

As you've pointed out, it also has some drawbacks. And I don't personally know if I'd use it in this scenario (in place of my custom Hook). But I definitely think that useCallback() is a better alternative than useEffect(). And I'm thinking that, in some other scenarios where useEffect() drives me nuts, it might be because I should really be using useCallback()...