Created
April 16, 2022 05:54
-
-
Save joshparkerj/36ce1baffbb079e691bf2da6b5d2f9ae to your computer and use it in GitHub Desktop.
example of how to use an effect only once even though strict mode remounts the component
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import React from 'react' | |
| import {useState, useEffect, useRef} from 'react' | |
| function App() { | |
| const [ques, setQues] = useState([]) | |
| const gettingQuiz = useRef(false) | |
| const getQuiz = async ()=>{ | |
| gettingQuiz.current = true | |
| const url = "https://opentdb.com/api.php?amount=10" | |
| const res = await fetch(url) | |
| const data = await res.json() | |
| console.log(data.results[0]) | |
| setQues(data.results) | |
| } | |
| useEffect(()=>{ | |
| !gettingQuiz.current && getQuiz() | |
| },[]) | |
| return ( | |
| <div>App</div> | |
| ) | |
| } | |
| export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment