2

After many infinite loops, I got the state to work and the page reloads on the click of my own refresh button.

I watched a few useMemo() and useCallback() tuts on Youtube but I haven't used the hooks enough to understand them. I was able to get it working but was wondering if anyone wanted to advise or hint at a better way to proceed...?

Also the useEffect with a variable dependency array didn't work for me though it seemed like the best solution originally.

function NavButtons(props) {
    const [refresh, setRefresh] = useState(false);
    function Refresh () {
        window.location.reload(true);
    }
    return (
        <div>
            <RefreshIcon onClick={Refresh} />         
        </div>
    );
};
SamiElk
  • 2,272
  • 7
  • 20
Andi
  • 31
  • 3
  • 1
    Actually the solution here is not updating state. – Andi Feb 01 '22 at 20:56
  • Yes, you're not using the state. Why do you want to reload the page? – SamiElk Feb 01 '22 at 21:03
  • Because there is a Math.random function running on an array of news on every refresh. So I wanted to give the user a button on the page so they don't have to rely on browser buttons to refresh the news. – Andi Feb 01 '22 at 21:22
  • You could set the result of that function in the state and call that function onClick. Usually with React you don't need to reload a page. – SamiElk Feb 01 '22 at 21:27
  • I will have to figure out what initial state to use. – Andi Feb 01 '22 at 21:34
  • You can use an empty array. Then you call the function the first time in a useEffect with an empty dependencies array. – SamiElk Feb 01 '22 at 21:35
  • "*Because there is a `Math.random` function running on an array of news on every refresh*" -- then you could just rerun the part of code responsible for generating the numbers. Store *those numbers* in a state, so your app will rerender automatically when they're changed. Reloading the entire page for that (especially that you're instructing the browser to redownload cached stuff) is a huge overhead for this! – FZs Feb 02 '22 at 06:17
  • Hmmm... I see your point about the overhead. Ok let me try to work it out. – Andi Feb 02 '22 at 20:27
  • ```const integer = Math.floor(Math.random() * 7)``` ```return topNews[integer]``` – Andi Feb 02 '22 at 20:37
  • That's the part of the code responsible for generating the numbers. – Andi Feb 02 '22 at 20:41

0 Answers0