geek glance
geek glance

Reputation: 111

React How to trigger page reload on state change

I want to reload my page when a state changes. Right now I am using the below code but don't know why it's reloading continuously even if the state is not changed.

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

Upvotes: 1

Views: 3241

Answers (1)

Gulam Hussain
Gulam Hussain

Reputation: 1763

useEffect will always excute after first render, and in your case even if state doesn't change it will reload the page on first render. i think you should add check in useEffect something like this

function YourComponent(){
    const initialState = "initial state";
    const [state, changeState] = useState(initialState);
    useEffect(()=>{
        // on first render, state will be initial state, so it will 
        // not reload, but on subsequent state change, it will reload the page
        if(state!==initialState){
            window.location.reload()
        }
    }, [state]);
}   

Upvotes: 2

Related Questions