React - useEffect
useEffect
is a React Hook that lets you synchronize a component with an external system.
useEffect(setup, dependencies?)
In my experience, it mainly used for initialization
or need to use some variables
to render the current component
Reference
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]);
// ...
}