xxxxxxxxxx
useEffect in react js
we’ll use the Effect Hook to run some JavaScript code after each render, such as:
1) fetching data from a backend service
2) subscribing to a stream of data
3) managing timers and intervals
4) reading from and making changes to the DOM
Why after each render?
Most interesting components will re-render multiple times throughout their lifetime and these key moments present the perfect opportunity to execute these “side effects”.
There are three key moments when the Effect Hook can be utilized:
1) When the component is first added, or mounted, to the DOM and renders
2) When the state or props change, causing the component to re-render
3) When the component is removed, or unmounted, from the DOM.
xxxxxxxxxx
import React, { useEffect } from 'react';
export const App: React.FC = () => {
useEffect(() => {
}, [/*Here can enter some value to call again the content inside useEffect*/])
return (
<div>Use Effect!</div>
);
}
xxxxxxxxxx
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
function Reddit() {
// Initialize state to hold the posts
const [posts, setPosts] = useState([]);
// effect functions can't be async, so declare the
// async function inside the effect, then call it
useEffect(() => {
async function fetchData() {
// Call fetch as usual
const res = await fetch(
"https://www.reddit.com/r/reactjs.json"
);
// Pull out the data as usual
const json = await res.json();
// Save the posts into state
// (look at the Network tab to see why the path is like this)
setPosts(json.data.children.map(c => c.data));
}
fetchData();
}); // <-- we didn't pass a value. what do you think will happen?
// Render as usual
return (
<ul>
{posts.map(post => (
<li key={post.id}>{post.title}</li>
))}
</ul>
);
}
ReactDOM.render(
<Reddit />,
document.querySelector("#root")
);
xxxxxxxxxx
import { useState, useEffect } from 'react';
function App() {
const [pieceOfState, setPieceOfState] = useState(0);
useEffect(() => {
console.log('I\'m in useEffect!');
console.log('This will be called whenever an instance of this component mounts');
console.log('or whenever pieceOfState is updated');
}, [pieceOfState]);
return (
<div>
<button onClick={() => setPieceOfState(pieceOfState + 1)}>Click Me to Update pieceOfState!</button>
</div>
);
}
xxxxxxxxxx
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
xxxxxxxxxx
import React, { useEffect, useState } from 'react';
const [count,setCount] = useState(0);
//The effect runs after each render since no dependencies are specified.
//run each render
useEffect(() => {
console.log("no depencies, no test");
})
//The effect runs once after the initial render due to the empty dependency array.
//only run start
useEffect(() => {
console.log("include depencies, no test");
},[])
//The effect runs after the initial render and whenever the count state variable changes.
//run start render and when changing count
useEffect(() => {
console.log("include depencies and test");
},[count])
return(
<div classsName="container">
<h2>{count}</h2>
<button onClick={() => setCount(count + 1)} > click </button>
</div>
xxxxxxxxxx
import React, { useState, useEffect } from 'react'
export default function App() {
const [count, setCount] = useState(0)
const color = count % 5 === 0 ? 'red' : 'blue'
useEffect(() => {
document.body.style.backgroundColor = color
}, [color])
return (
<button
onClick={() => {
setCount(count + 1)
}}
>
Click HERE to increment: {count}
</button>
)
}
xxxxxxxxxx
import { useEffect } from 'react';
import { createConnection } from './chat.js';
function ChatRoom({ roomId }) {
const [serverUrl, setServerUrl] = useState('https://localhost:1234');
useEffect(() => {
const connection = createConnection(serverUrl, roomId);
connection.connect();
return () => {
connection.disconnect();
};
}, [serverUrl, roomId]);
// ...
}
xxxxxxxxxx
import React, { useState, useEffect } from 'react';
function Example() {
const [count, setCount] = useState(0);
// Similar to componentDidMount and componentDidUpdate:
useEffect(() => {
// Update the document title using the browser API
document.title = `You clicked ${count} times`;
});
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
Source:reactjs.org
3
React useEffect, useState
xxxxxxxxxx
useEffect(() => {
const dialog = dialogRef.current;
dialog.showModal();
return () => dialog.close();
}, []);
xxxxxxxxxx
What does useEffect do? By using this Hook, you tell React that
your component needs to do something after render.
React will remember the function you passed (we’ll refer to it
as our “effect”), and call it later after performing the DOM updates.