I’m trying to figure out a way which I can load data from the database only once to a certain component.
useEffect(() => {
axios.get("http://localhost:5000/members")
.then(res => {
setMembers(res.data)
})
catch(error => console.error(error.message))
})
Every time this component is loaded a request is made to the server for the "members". I need a way to make a request only one time, and which is when the component is being loaded for the very 1st time. Is there a way I can go about achieving this?
4
Answers
You are doing one mistake here with useEffect as second argument not passed.
Make the request outside your component’s function. Promises only resolve once but the resolved value can be retrieved any number of times.
You can see in the demo that the same component is loaded 3 times but the request is only made once.
You can use Context to persist data throughout application or
you can use redux for storing data in centralized app state.
You only need to add
[]
at the end of the useEffect hook in React. When a component loads data, it will not run this useEffect multiple times.