0

I have a variable isVisible that holds a boolean value. When this variable changes, I need to make a reload of the component, but only one time. And if the variable changes again at some point, then run this reload again for one time, but not continuously. Currently, I have this code that runs continuously:

useEffect(() => {
    if (isVisible) {
        window.location.reload();
    }
}, [ isVisible ]);

How is this possible to achieve? Can someone tell me why this component is reloading continuously, even when I add the variable in dependency array?

1
  • You are reloading the entire page, unless you use some form of local storage to prevent it, that variable will change (when it's initialised) every time the page loads, triggering the effect (and reloading the page, etc) Why do you need to reload the page? Commented Jan 18, 2022 at 14:04

1 Answer 1

2

Note: Reloading the entire website to reload a component is a not good method in react. if only need to reload a component you could try changing its key from the parent component.

For this particular case (If you really need to do reloading try this)

create state to check whether its first load or not

const [isFirstLoad, setIsFirstLoad] = useState(true)
const [isVisible, setVisible] = useState(false)
useEffect(() => {
    if (!isFirstLoad) {
        window.location.reload();
    } else {
        setIsFirstLoad(false)
    }
}, [ isVisible ]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.