Skip to content

Instantly share code, notes, and snippets.

@ravisiyer
Last active February 8, 2024 07:59
Show Gist options
  • Save ravisiyer/c00d50e838aa69aa3b36f03c9bcadf6d to your computer and use it in GitHub Desktop.
Save ravisiyer/c00d50e838aa69aa3b36f03c9bcadf6d to your computer and use it in GitHub Desktop.
Notes on React useEffect - App.js
import { useEffect, useState } from "react";
const TestForm = ({ handleSubmit }) => {
const [formPostTitle, setFormPostTitle] = useState("");
const [formPostBody, setFormPostBody] = useState("");
useEffect(() => {
function cleanUp() {
console.log("TestForm:useEffect cleanUp fn. invoked");
}
console.log("TestForm:useEffect setup fn. invoked");
return cleanUp;
}, []);
return (
<form
className="TestForm"
onSubmit={(e) => {
e.preventDefault();
handleSubmit(formPostTitle, formPostBody);
}}
>
<h3>TestForm</h3>
<label htmlFor="title">Title: </label>
<input
type="text"
id="title"
autoFocus
value={formPostTitle}
onChange={(e) => setFormPostTitle(e.target.value)}
/>
<label htmlFor="body">Post Body: </label>
<textarea
id="body"
value={formPostBody}
onChange={(e) => setFormPostBody(e.target.value)}
/>
<p>
<button type="submit">Set App Post Title and Body</button>
</p>
</form>
);
};
const App = () => {
const [appPostTitle, setAppPostTitle] = useState("");
const [appPostBody, setAppPostBody] = useState("");
const [showForm, setShowForm] = useState(false);
useEffect(() => {
function cleanUp() {
console.log(
"App:useEffect cleanUp fn. invoked. appPostTitle is: " + appPostTitle
);
}
console.log(
"App:useEffect setup fn. invoked. appPostTitle is: " + appPostTitle
);
return cleanUp;
}, [appPostTitle]);
function handleSubmit(submittedPostTitle, submittedPostBody) {
setAppPostTitle(submittedPostTitle);
console.log(
`App component: handleSubmit() called and has set appPostTitle to: ${submittedPostTitle}`
);
setAppPostBody(submittedPostBody);
}
function handleClick(e) {
setShowForm(!showForm);
}
return (
<div>
App for testing useEffect(). Components having useEffect() and associated
dependencies:
<ul>
<li>App</li>
<ul>
<li>
useEffect() with App. component's Post Title (appPostTitle) as
dependency
</li>
</ul>
<li>TestForm</li>
<ul>
<li>useEffect() with empty dependency array</li>
</ul>
</ul>
<p>
See console log to know when useEffect() setup and cleanup functions are
invoked as you show/hide the form and submit the test form which sets
App component's Post Title and Post Body.
</p>
<br />
{showForm && <TestForm handleSubmit={handleSubmit} />}
<h3>App</h3>
<button onClick={handleClick}> Toggle Show/Hide TestForm</button>
<p>App Post Title: {appPostTitle}</p>
<p>App Post Body: {appPostBody}</p>
</div>
);
};
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment