Skip to content

Commit

Permalink
Tipify use-effect-once
Browse files Browse the repository at this point in the history
  • Loading branch information
Chalarangelo committed Sep 4, 2024
1 parent 90b176c commit f2a0fff
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions content/snippets/react/s/use-effect-once.md
Original file line number Diff line number Diff line change
@@ -1,23 +1,27 @@
---
title: React useEffectOnce hook
type: snippet
shortTitle: useEffectOnce hook
type: tip
language: react
tags: [hooks,effect]
cover: pop-of-green
excerpt: Runs a callback at most once when a condition becomes true.
excerpt: Run a callback at most once when a condition becomes true, using a custom React hook.
listed: true
dateModified: 2021-11-16
dateModified: 2024-06-26
---

Runs a callback at most once when a condition becomes true.
The way `useEffect()` works in React is that it runs every time the component renders. Sure, you can control when it runs by providing a dependency array, but what if you want it to **run only once** when a condition becomes `true`? You can create a custom hook to achieve this.

- Use the `useRef()` hook to create a variable, `hasRunOnce`, to keep track of the execution status of the effect.
- Use the `useEffect()` that runs only when the `when` condition changes.
- Check if `when` is `true` and the effect has not executed before. If both are `true`, run `callback` and set `hasRunOnce` to `true`.
As mentioned already, the second argument of the `useEffect()` hook is an **array of dependencies**. When any of these dependencies change, the effect runs. By using a `useRef()` hook to keep track of the **execution status** of the effect, you can ensure that the effect runs only once when the condition becomes `true`.

Then, inside the `useEffect()`, you can check if the condition is `true` and the effect **has not executed before**. If both are `true`, you can run the callback and set the execution status to `true`.

In order to then use the custom hook, you can pass the callback and the condition as arguments, same as a regular `useEffect()` call. The custom hook will then run the callback at most once when the condition becomes `true` the first time.

```jsx
const useEffectOnce = (callback, when) => {
const hasRunOnce = React.useRef(false);

React.useEffect(() => {
if (when && !hasRunOnce.current) {
callback();
Expand Down

0 comments on commit f2a0fff

Please sign in to comment.