how to toggle a boolean state in react
toggle a boolean state in react:
-
use
usestate
the hook to track the state of a boolean value. -
pass a function to
setstate
the function returned by the hook. -
toggle a boolean value depending on its current value,
setisloading(current => !current)
e.g.
import {usestate} from 'react';
export default functionapp() {
// 👇️ initialize boolean to false
const [isloading, setisloading] = usestate(false);
const toggleisloading = () => {
// 👇️ passed function to setstate
setisloading(current => !current);
};
return (
<div><buttononclick={toggleisloading}>toggle loading statebutton>
{isloading && <h2>loading...h2>}
div>
);
}
we setisloading
pass a function to , because isloading
that function is guaranteed to be called with the current (latest) value of the boolean.
in the example, we simply toggle the boolean and return the result to update the state.
we use logical not (!)
operators to flip boolean values.
following are some examples of using the logical not operator.
console.log(!true); // 👉️ false console.log(!false); // 👉️ true
注意
, we should not try to access a boolean state variable immediately after changing it.
setisloading
if we try to access a state variable immediately after updating it
using the function isloading
, there is no guarantee that we will get the current (latest) value.
if we need to listen to state changes, add the state variable to useeffect
the dependencies array of the hook.
import {useeffect, usestate} from 'react';
export default functionapp() {
const [isloading, setisloading] = usestate(false);
const toggleisloading = () => {
// 👇️ passed function to setstate
setisloading(current => !current);
};
useeffect(() => {
// 👇️ 如果我们需要监听 isloading 布尔值的变化
console.log('isloading is: ', isloading);
}, [isloading]);
return (
<div><buttononclick={toggleisloading}>toggle loading statebutton>
{isloading && <h2>loading...h2>}
div>
);
}
we added the isloading state variable to the hook's dependencies array, so any time isloading changes, useeffect
the logic in our hook will re-run.
注意
, which is also called when mounting a component.
if we don't want to run the logic in the hook on the initial render useeffect
, but only when a specific state variable changes, use a ref to return early on the initial render.
import {useeffect, usestate, useref} from 'react';
export default functionapp() {
const [isloading, setisloading] = usestate(false);
const toggleisloading = () => {
setisloading(current => !current);
};
const isfirstrender = useref(true);
useeffect(() => {
if (isfirstrender.current) {
isfirstrender.current = false;
return; // 👈️ return early if first render
}
console.log('isloading is: ', isloading);
}, [isloading]);
return (
<div><buttononclick={toggleisloading}>toggle loading statebutton>
{isloading && <h2>loading...h2>}
div>
);
}
when running the hook on mount useeffect
, we use ref to exit early.
use this method if we want to listen to state changes but need to skip the first render.
for reprinting, please send an email to 1244347461@qq.com for approval. after obtaining the author's consent, kindly include the source as a link.
article url:
related articles
creating a back button with react router
publish date:2025/03/10 views:155 category:react
-
使用 react router 创建后退按钮: 将按钮上的 onclick 属性设置为函数。使用 usenavigate() 钩子,例如 const navigate = usenavigate();。调用 navigate() 函数,传递它 -1 - navigate(-1)。
how to create a read more/less button in react
publish date:2025/03/10 views:168 category:react
-
在构建 web 应用程序时,有时我们需要显示一些长文本。在这种情况下,一个聪明的设计是只显示部分文本并添加一个显示更多按钮供用户在需要时展开文本。当文本已展开并完全显示时
insert style tags into react components
publish date:2025/03/10 views:66 category:react
-
要在 react 组件中插入样式标签,请将我们的 css 包装在样式标签中的模板字符串中。 花括号之间的表达式将被评估并添加样式。
publish date:2025/03/10 views:179 category:react
-
使用 useeffect 钩子来监听 react 中的状态变化。 我们可以将要跟踪的状态变量添加到挂钩的依赖项数组中,并且每次状态变量更改时都会运行 useeffect 钩子中的逻辑。
get parent height and width in react
publish date:2025/03/10 views:158 category:react
-
在 react 中获取父级的高度和宽度: 在元素上设置 ref 属性。 在 useeffect 钩子中,更新高度和宽度的状态变量。 使用 offsetheight 和 offsetwidth 属性来获取元素的高度和宽度。
get the value of an input field in react
publish date:2025/03/10 views:179 category:react
-
要在 react 中获取输入字段的值: 声明一个跟踪输入字段值的状态变量。 将 onchange 属性添加到输入字段。 使用 event.target.value 获取输入字段的值并更新状态变量。
rendering nested arrays in react using map()
publish date:2025/03/10 views:71 category:react
-
使用 map() 渲染嵌套数组: 使用 map() 方法迭代外部数组。 在每次迭代中,调用嵌套数组的 map()方法。 渲染嵌套数组的元素。
publish date:2025/03/10 views:118 category:react
-
在 react 中获取表单提交的输入值: 将输入字段的值存储在状态变量中。在表单元素上设置 onsubmit 属性。 在我们的 handlesubmit 函数中访问输入字段的值。
publish date:2025/03/10 views:130 category:react
-
在 react 中为 body 元素添加一个类: 在 useeffect 或事件处理程序中以 document.body 的形式访问 body 元素。 使用 classlist.add() 方法将类添加到 body 标记。 例如,document.body.classlist.add('my-class'