React Hooks Are Easy to Use Within Minutes

Seann Branchfield
Apr 14, 2020 · 2 min read

React hooks are a way to be able to use state with a functional component. Since class components are typically used to access state and lifecycle methods, this is a way of being able to have some of those features within a functional component. If you want to use them, they can be set up very quickly.

useState and useEffect

These hooks are both easy to use and can be added to the import line.

How useState works: You define a state variable and a function to update it in a destructured array. The useState function you need to give some sort of initial value. In this instance I am making a button that controls a boolean value so I chose to set it to false. This is defined prior to the return statement.

const [festivalsOpen, setFestivalsOpen] = useState(false)

After that I made a button which calls setPanelOpen and switches the value of panelOpen between true and false.

A conditional statement below that renders one of two <p> tags.

How useEffect works: This in a way replaces some of the lifecycle methods. When useState is called you can define useEffect to do something.

In this instance I just have a console.log that outputs the newest value of festivalsOpen.

If you want a detailed description of how and why this works, the documentation for React is quite good. This is a decent alternative to using a class component in certain situations.

The Startup

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store