44

I was working on react project. I was trying to reload a component when we click the reload button. I implemented the onClick function as given below. But it is reloading the whole window. I just want to reload only that class component, not the whole window. Can anyone help me to solve this?

refreshPage() {
    window.location.reload();
  }
5
  • 1
    You are supposed to change the state in order to re-render something. Commented Jun 18, 2019 at 12:24
  • @MuratKaragöz Can you give example? Commented Jun 18, 2019 at 12:28
  • reactjs.org/docs/state-and-lifecycle.html Commented Jun 18, 2019 at 12:30
  • do you also want to call componentDidMount for some nested components as well? if you do, I see only possible solution to change key prop for topmost element in part you want to "update" Commented Jun 18, 2019 at 12:38
  • 1
    Why do you need this to reload? Generally if a component needs to be visually updated, the props and/or state should be changing anyway. Could you elaborate on what you're trying to accomplish? Commented Jun 18, 2019 at 12:41

12 Answers 12

50

The easiest way I have found out is to set a seed state, and use that in the key attribute of the rendered component. Whenever the seed changes now the component will be reloaded.

       const [seed, setSeed] = useState(1);
       const reset = () => {
            setSeed(Math.random());
        }
       <Component key={seed}/>
       <Button onClick={reset}>Reset</Button>

Whenever the Reload button is pressed now the component I need will be rerendered.

Sign up to request clarification or add additional context in comments.

2 Comments

Hey @Ezeeroc happy to know that it works for you as well
Nice solution, especially when working with for loops in jsx!
30

If you just want to reload the component's data, use the useEffect Hook:

useEffect(() => {
    fetchData();
}, [data]);
// fetchData() is called whenever data is updated.

Comments

8

You can trigger a reload of components by updating the state.

class YourComponent extends Component {
  state = {
    reload: false
  };

  refreshPage = () => {
    this.setState(
      {reload: true},
      () => this.setState({reload: false})
    )
  }
}

This is dirty, but it may work. I have not tested it, though.

4 Comments

How will it reload and how the state variables be tracked?
Anything that occurs in render() re-runs. It Reacts to state changes.
will it call componentDidMount again?
It shouldn't, no. If you need to do that, it may be that you're using the lifecycle events wrong.
3

If you'd like to use "hard reload" (remove component and recreate it) instead of forcing child components to just re-render themselves but of course without page reloading, I prepared reload hook:

export function useReload(): [() => void, boolean] {
    const [reloading, setReloading] = useState(false);
    const reload = useCallback(() => {
        setReloading(true);
    }, [setReloading]);

    useEffect(() => {
        if (reloading) {
            setReloading(false);
        }
    }, [reloading, setReloading]);

    return [reload, reloading];
}

Usage of it is simple and clean:

const [reload, reloading] = useReload();

return <>
    <button onClick={reload}>reload component below</button>
    {reloading ? null : <ComponentToReload />}
</>;

1 Comment

this hook was exactly what i was looking for, thank you a bunch!
2

You can create a new function. And you can call it on componentDidMount and refreshPage.

exampleFunction = () => {
   /** Do your job here */
}

componentDidMount(){
   /** your code */
   this.exampleFunction ();
   /** your code */
}

refreshPage(){
   this.exampleFunction ();
}

6 Comments

this.forceUpdate() doesnot produce any result
want to highlight: that will not call componentDidUpdate, componentDidMount or constructor's code. just re-renders.
this method skips shouldComponentUpdate(), you can read more about here reactjs.org/docs/react-component.html#forceupdate
@skyboyer I want to call componentDidmount also. Then forceUpdate() may not work
@Gauranga, I think you want to get data again on click of refresh button. right ?
|
1
refreshPage() {
  window.location.reload(false);
}

Reference at here: https://upmostly.com/tutorials/how-to-refresh-a-page-or-component-in-react

1 Comment

This will still reload the entire page, which is not what was asked for, and adding a false is a behavior that only has any meaning on Firefox developer.mozilla.org/en-US/docs/Web/API/Location/reload and not the desired behavior
0

If you want render your component then you can update any state using this.setState({}) in your function.

3 Comments

Will it call componentDidMount on reload. I want this to happen?
I think it will call componentDidMount because componentDidMount calls after render.
No. It will not call componentDidMount as the component is already mounted. It will call componentDidUpdate.
0

window.location.reload(); will reload the current document, it like the Refresh button in browser, and it will not make any partial re rendering like AJAX. To achieve this by make setState in react.

Below the working sample :

import React from "react";

class RefreshComponent extends React.Component {
 constructor(props) {
   super(props);
   this.state = { name: "React Component reload sample" };
}
 submit() {
   this.setState({ name: "React Component Updated - " + new Date() });
}
render() {
  return (
    <div>
      {this.state.name}
      <br />
      <button
       onClick={() => {
         this.submit();
       }}
     >
       Submit
     </button>
    </div>
  );
 }
}

export default RefreshComponent;

Comments

0

The most maintainable way is to reactor existing components to handle "reload" in consistent way. ideally components should get data though props/context/redux instead of loading that on their own. This way you can refresh all with single call. Say it may be redux with some action like "REFRESH_HOTELS" or separate context with method reload.

as a last resort you may update key prop(to any other value, maybe just random string) and whole branch will be recreated including call to componentDidMount. it's know as "reset state by key prop" technique. but it's neither performance-safe nor really flexible way. better to avoid that until you really don't care of maintainability(or use as temporary solution... but typically "temporary solutions" stays as long as app exists)

Comments

0

You can check out this other thread: Can you force a React component to rerender without calling setState?

This is the top answer:

In class components, you can call this.forceUpdate() to force a rerender.

Documentation: https://facebook.github.io/react/docs/component-api.html

In function components, there's no equivalent of forceUpdate, but you can contrive a way to force updates with the useState hook.

Comments

0

I had the same problem and every time I tried to reloaded my component, It would just turn into a non-stop reloading loop. here's how I fixed it, hope it works for you:

useEffect(() => {
 // Get the reloaded value from localStorage
 const storedValue = localStorage.getItem("reloadWindow");

// Check if storedValue is null or undefined or 0
 if (
   storedValue === null ||
   storedValue === undefined ||
   storedValue === "0" // this is because I had set to 0 when i logged out
 ) {
      window.location.reload();
      // Set the value in localStorage
      localStorage.setItem("reloadWindow", JSON.stringify(1));
 }
}, []);

Comments

0

you just need to do in useEffect

if you have data in useState

let [data, setData] = useState([]);

whenever the data has changes, it automatically reload the component

useEffect(()=>{
   
     },[data]) 

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.