Hello everyone!
First thing I will say is, using the method I am about to talk about is not recommended. It should be used only when you are really desperate, nothing works otherwise, and using it might help you find the problem in your code.
Now that we've cleared that out of the way, lets get started!
So to begin with - Yes, it is weird, but React isn't... reactive. I could go into details, but why do something when others have already done it for us?
One of the issues every junior React developer will come by at some point:
"My code works, console.log prints what it should, but nothing is showing right!"
Obviously your usual answer could be something like: "You gotta use the 'useState' hook right there", or you would dive deeper into the code to find the problem easily, but lets say things are not that simple in this specific scenario and that for some weird reason your attempt at 'useState' did not get you the results you needed.
So what can you do?
Add a conditional rendered fragment!
What is that?
Basically this:
{state && <></>}
Just add that to your main file - App.js, index.js, whatever you are using - and 'render' that nothingness.
Dont forget to include:
const [state, useState] = React.useState(false);
in the same file, and -
setState(!state);
...when you want to force a render.
It is a bit weird if you think about it, since you are rendering... nothing. But it works. Interesting by itself.
I hope reading this has helped you solve errors in your code, expand your knowledge, or even that you just had fun exploring this.
Were you amused? let me know in the comments.
Top comments (0)