TIA
a code block featuring a react component

How to toggle state in React

react

April 03, 2022

Toggling state is a very useful thing to know about when you’re learning React. Luckily, it’s actually a very simple thing to do!

Below is a React functional component. It contains some state, a function, and some stuff to be rendered.

The component will render a div containing a button and some text that says “Hello, world!“…but hang on! The text actually won’t be visible initially! Do you know why?

a code block featuring a react component

The reason why the text is hidden initially is because we’ve chosen to conditionally render it, based on whether showText is true or false. That’s what this bit is doing:

{showText && <h1>Hello, world!</div>}

It means, if the value of showText is true, render the h1 component.

To begin with, we’ve set the state of showText to false. However, we can change this at the click of a button!

The button in the component triggers the toggleFunc function. Within this function, the state setter setShowText is called.

setShowText(!showText)

…but what’s with the exclamation mark? Why didn’t we just say: setShowText(true) ?

Well, this is how we toggle. Each time we click the button, we don’t want it to just be set to true; we want it to toggle to the opposite of what it was before eg. true -> false, false -> true, so we can alternative between showing or hiding the text.

Putting the question mark before the state (showText) is part of JavaScript functionality (the logical “not” operator) and it transforms the state to the opposite boolean value (so it will make true -> false and false -> true).

So that’s how you toggle state in React! Simple huh?


Profile picture

Written by Tia Eastwood, software developer, React enthusiast and cat lover.