diff --git a/README.md b/README.md index d8b51a6..44ee89e 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ smart people at [Hashrocket](http://hashrocket.com/). For a steady stream of TILs from a variety of rocketeers, checkout [til.hashrocket.com](https://til.hashrocket.com/). -_839 TILs and counting..._ +_840 TILs and counting..._ --- @@ -573,6 +573,7 @@ _839 TILs and counting..._ - [Spelunking Through Components With Enzyme's Dive](react/spelunking-through-components-with-enzymes-dive.md) - [Sync Your react-router State With Redux](react/sync-your-react-router-state-with-redux.md) - [Test Files In create-react-app](react/test-files-in-create-react-app.md) +- [Trigger Effect Only When The Component Mounts](react/trigger-effect-only-when-the-component-mounts.md) - [Update Formik Initial Values When Props Change](react/update-formik-initial-values-when-props-change.md) - [Upgrading To The Latest React In CodeSandbox](react/upgrading-to-the-latest-react-in-codesandbox.md) - [Use A Ref To Autofocus An Input](react/use-a-ref-to-autofocus-an-input.md) diff --git a/react/trigger-effect-only-when-the-component-mounts.md b/react/trigger-effect-only-when-the-component-mounts.md new file mode 100644 index 0000000..fc65cb0 --- /dev/null +++ b/react/trigger-effect-only-when-the-component-mounts.md @@ -0,0 +1,36 @@ +# Trigger Effect Only When The Component Mounts + +With `useEffect`, you generally want to values used in the function to also be +included in the _dependency list_. This ensures the effect is triggered +whenever any of those values change. + +But what if you only want the effect to be triggered when the component first +mounts? + +This can be done by including an _empty_ dependency list. + +```javascript +import React, { useState, useEffect } from "react"; + +function App() { + const [count, setCount] = useState(0); + const incrementCount = () => { + setCount(prevCount => prevCount + 1); + }; + + useEffect(() => { + console.log("The count is:", count); + }, []); + + return ( +
Count: {count}
+