Zum Inhalt springen

Understanding dependencies array & useEffect() visually (ReactJS)x`

useEffects accepts two arguments. First the callback function or effect code. Second, the dependencies array.

Interact and Learn Yourself Here

We use useEffect() hook to manage side effects, Imagine side effects as simply the operations which change something outside of our component. To handle changes inside our components we have useSate.

The dependencies array

  • The dependencies array is crucial to understand. It sets the conditions for when the useEffect() will run again. If we do not pass it, the useEffect() runs on every re-render of component. This can be expensive. Think about every time it fetches data from external API.

useEffect(() => { // Runs on initial render AND every update console.log('Component rendered or updated'); }); 
  • Passing null (“ „) dependencies array. It will run the useEffect() hook after the first render of the component only. It will not run useEffect() after subsequent updates of the components.

useEffect(() => { // Runs only once after the first render fetchData(); }, ); 
  • Passing Dependency Array with Values. Passing value to Dependency Array ensure that it will run the useEffect() only after first render and when value of dependency array changes.

useEffect(() => { // Runs when the component mounts and whenever `userId` changes fetchUserData(userId); }, [userId]); 

submitted by /u/BeyondITBLOG2
[link] [comments]

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert