How to force useEffect to be called every time component is called?
Example
// Child component const ChildComponent = () => { useEffect(() => { // Do something }, []) return <></> } export default ChildComponent
// Parent component import React from 'react' import {MenuButton} from './components' import ChildComponent from '../child-component'; import ReactDOM from 'react-dom' const Home = () => { const onClick = () => { $(":mobile-pagecontainer").pagecontainer("change", '#ChildComponent', { transition: "slide", reverse: false }) ReactDOM.render(<ChildComponent />, document.getElementById('id-child-component)) } return <> <div onClick={onClick}> <MenuButton title={'Open child component'}> </div> </> } export default Home
Solution
// Child component const ChildComponent = ({isRefresh, refreshComponent}) => { useEffect(() => { // FIX HERE!! refreshComponent() // Do something }, [isRefresh]) return <></> } export default ChildComponent
// Parent component import React, {useState} from 'react' import {MenuButton} from './components' import ChildComponent from '../child-component'; import ReactDOM from 'react-dom' const Home = () => { // ADD THIS const [isRefresh, setIsRefresh] = useState(false) const refreshComponent = () => { setIsRefresh(!isRefresh) } const onClick = () => { $(":mobile-pagecontainer").pagecontainer("change", '#ChildComponent', { transition: "slide", reverse: false }) // FIX HERE!! ReactDOM.render(<ChildComponent refreshComponent={refreshComponent} isRefresh={isRefresh} />, document.getElementById('id-child-component)) } return <> <div onClick={onClick}> <MenuButton title={'Open child component'}> </div> </> } export default Home
By this way, every time you are back to parent component and open child component, useEffect in child component is called!
Leave a Reply