React Abominations: Is this Legal?

Hey!

I've been learning React recently, and handling error messages separately in my React Project, and wondered 🤔:

"What if you can merge them together?"

So I tried this:

useErrors.js

Code 1

It's pretty self-explanatory, but essentially I define a useErrors function that creates an error state. Then, within that same function, I create an Error Component, which checks if an error exists. If no error exists, it is set to false; any other value would mean that there is an error.

Thus, the Error Component renders accordingly, and the useErrors function returns that Error Component, along with the setError function.

Usage:

test.js

Code 2

The useErrors function is handled 4 ways:

import useErrors from "./useErrors"; - imports the function.

const [Error, setError] = useErrors(false); - creates the Error state, passing in the default error value (a value of false is automatically hidden), and returns the Error Component, as well as the setError function.

setError([<value> | false); - invokes the function to set the error message. A value of false is hidden; any other value is displayed as the error message.

<Error /> - the JSX to render the error message. (Notice no props are sent, yet it works?)

When running the code, the error is displayed:

Error 1 Pic

And, when ready, it can be closed (which just sets the error state to false)

More Testing:

To further test, we can create a loop that sets random error messages and clears them:

test.js

Code 3

Error 2 Gif

It even works when you create multiple Error States (different names for different messages), and you could reuse the same Error Component multiple times on the page and it'll React the same for that setError:

Error 3 Gif

But... how? Why?

From my understanding, React Components are reusable, either if they're functional or class-based. And the usual way data is sent/updated per Component is either through state or props. So how does a variable from a parent function run down into that Component, while being unique to that one instance of error message?

  • Is any data leak happening?
  • Are there resources out there that can educate me on what I'm currently doing?
  • Is this bad practice? I lack knowledge of the terminology for such a thing, all I know is...it works
  • Until I've successfully created commenting on posts to this website, you can find me on Twitter @danidre or join my Discord server. Feel free to message me on the Nodeiflux server and share your thoughts!

    It's possible it's wrong...but it works! 😉

    5049 views | Feb 21, 2020, 3:14 PM