• Skip to primary navigation
  • Skip to main content
Sal Ferrarello
  • About Sal Ferrarello
  • Speaking
  • Connect
    Mastodon GitHub Twitter (inactive)
You are here: Home / Dev Tips / WordPress Gutenberg Functional Component useState

WordPress Gutenberg Functional Component useState

Last updated on March 30, 2020 by Sal Ferrarello

When creating a block for the WordPress block editor (a.k.a. Gutenberg), I find that most of the documentation is for class components. However, with React hooks we can use functional components.

When you need to import useState from react, you can do it as follows in a WordPress block.

const {
    element: {
        useState,
    },
} = wp;

After this line useState is available for use.

Sal Ferrarello
Sal Ferrarello (@salcode)
Sal is a PHP developer with a focus on the WordPress platform. He is a conference speaker with a background including Piano Player, Radio DJ, Magician/Juggler, Beach Photographer, and High School Math Teacher. Sal can be found professionally at WebDevStudios, where he works as a senior backend engineer.

Share this post:

Share on TwitterShare on FacebookShare on LinkedInShare on EmailShare on Reddit

Filed Under: Dev Tips, Programming, Solution Tagged With: Gutenberg, WordPress

Reader Interactions

Comments

  1. Kelly says

    August 20, 2020 at 7:01 pm

    I keep getting an error when I try to use useState – I get it in both a plugin and a theme. Have you come across this? I can’t find a way around it.

    Error: Uncaught (in promise) Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.

    Reply
    • Alex says

      August 26, 2020 at 6:18 pm

      Same here. It borks the post if you save it. I can’t find much of any information regarding this.

      Reply
  2. Alex says

    August 26, 2020 at 6:28 pm

    https://github.com/WordPress/gutenberg/issues/16843

    Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Copyright © 2023 · Bootstrap4 Genesis on Genesis Framework · WordPress · Log in