How to use React Hooks in custom component

How do I use React hooks in my custom component. Specifically, I want to use useState() to manage local state without having to update the model and wait for a re-render triggered from the Retool side. Without something like useState, I find I have to put all kinds of internal state concerns into the component model, which isn't ideal in terms of component architecture, and it's slow to re-render.

1 Like

Hi @ruswerner!

The version of React used for custom components at the moment doesn't support hooks. If you'd like the functionality of useState you can try creating a React class as described here. Let me know if that works!

I'll give that a try. Thanks for the quick reply!

You can actually use hooks in custom components via React.useState and React.useEffect!

1 Like

Thanks for this callout @ezou! As of version 2.101 we've updated the default React version used in custom components from 16.7.0 to 18.2.0 :slightly_smiling_face:

1 Like

@Kabirdas, can you add some more detail on the updated React version:

  • The Retool Custom Component Boilerplate still points to react and react-dom on the Retool CDN which are both at 16.7.0.
  • If I don't include the JS files from the Retool CDN, I see that React is running in the parent context, but it's not available (or at least not defined as React) from the component's frame.

For reference, I'm on Retool 2.106.0.

Hey @tradesorg_chris, thanks for the callout!

The React version had been updated in the default code that's generated when creating a custom component. We've gone ahead and updated the custom component doc so that the examples there should also use React 18 as well :slightly_smiling_face:

The Retool CDN will continue to host React 16.7.0 for the moment, the updated component examples fetch from unpkg.

1 Like

Great - thanks for that update. Would it be possible for y'all to add some info on the Babel transpilation y'all have going?

I ran into an error when trying to use a spread operator and couldn't really diagnose what was going on without visibility into what y'all are doing to the text/babel code.

Thanks for surfacing this! It looks as though spread syntax generally isn't working with scripts that are getting transpiled. I've let the dev team know, we'll look into it on our end and report back!

1 Like

get the message "React.usestate is not defined"

Hey @peter.b! Would you mind posting a screenshot of the error? You may need to write React.useState specifically instead of React.usestate:

Turns out it was a combination of the incorrect react script version and an unwelcome typo :slight_smile: Thanks for your help