How can I call a global function in React? - javascript

Yesterday I had an interview for React developer position. Interviewer asked me about global functions and how to create and call global functions with React ?
I thought he is talking about Redux and state containers ...
But he said, no ... it's not about state containers and it's about react services.
Since after interview I searched about react services, but I didn't find any thing.
What do you think about this feature and global functions ? I should import global functions above all components or here is different method to handle this ?
Thanks

You have to describe what you call a "react service" and "global function" here, then it will be possible to say the answer how to get it done.
Any kind of "global" stuff, like the helper function which you need in many different places I would put in separate file and export it there and then import/require anywhere needed.
Traditionally, in the web app, the global function may be something added to the window object. Which is a bad pattern and it's well documented over the years. Just google on a topic.
"React service", for me, mostly reminds some API that can run server-side render to render the react app. Like API endpoint which you provide ReactJS app URL and it will spit back raw HTML. I would use headless chrome and global function in this context may be js running in page context running inside the chrome but this stuff is definitely out of the scope of ReactJS.
Another thing, it could be any kind of helper functions that provide some kind of data management, connection handling to something or almost whatever else.
I think the correct answer would be: Define what do you mean by "react service" and "global function".
Too many things could be called a service or global function.

Related

Why do we use the context API in React?

So I had this thought occur to me today. I've been learning React for a bit, and I often hear the Context API as a shared data source for nested components. You instantiate a context, wrap all the components you want to have access to in that context's provider, and do what you need to with that data inside each component.
My question then is essentially, why do we use the Context API instead of just using a shared reference to a value inside a module? At the end of the day the useContext hook and Context.Consumer require an amount of code roughly equivalent to simply importing a module across all the components that need access to its data.
I'm struggling to understand how using the Context API actually solves any problems that couldn't just as easily be solved with what the browser already provides us, so what am I missing here?

What's the best way to wrap Redux's API so that store instances are transient instead of singletons?

I haven't had a look at the source in-depth or anything yet, but was just curious if anyone has required or made use of this in the past or not.
It appears as though Redux is creating a singleton instance for the store and persisting this for the lifetime of the caller, but this is not really tenable for what we're thinking of implementing... what is the simplest approach, if one exists, for extending their API and creating stores with scoped lifetimes?
This is in the context of Redux being used in a purely server-side application (or at least as far as it can tell etc.)
Edit:
Similarly, while you can reference your store instance by importing it
directly, this is not a recommended pattern in Redux. If you create a
store instance and export it from a module, it will become a
singleton. This means it will be harder to isolate a Redux app as
a component of a larger app, if this is ever necessary, or to
enable server rendering, because on the server you want to create
separate store instances for every request.
I found this excerpt in their documentation here.
How does this module exporting consideration work in practice? If I only access the store within the scope I declared it for a given lifetime via externally exposed methods, should I expect the instance to be deallocated when the scope closes in some specified app lifetime?

Sharing data across React components

In front-end apps there is often data which needs to be accessed by many components. Routing is one example, another is configuration data, e.g. feature switches, default language, etc.
In an app that isn't using any particular framework, I might share this configuration data across modules using
export class Configuration {
static getConfig () {
// get the config from the server
return axios.get('/config').then(function (response) {
return response;
})
}
}
Then import this class into any module that needs to access configuration data. With some front-end framework, it's obvious how to share such "global" data, e.g.
AngularJS - Configuration should be defined as a service that's dependency-injected into any controllers/directives/services that need to access config. data
Vue.js - use a mixin
However, when using ReactJS it's not obvious which approach should be used. Possible options are:
A plain-old JavaScript module. Encapsulate the data to be shared as a function/method, and import it into any React components that need to access it. The seems like the simplest approach, but I have the feeling that when writing a ReactJS app everything should be defined as a component, rather than JavaScript classes/functions.
Redux seems to be recommended approach for sharing-state within large apps, but this feels like overkill for smaller projects
Something else?
but I have the feeling that when writing a ReactJS app everything
should be defined as a component, rather than JavaScript
classes/functions.
I really don't see a reason why everything should be a component in React. If it is just data, you can create a single instance of that JS object say and import that anywhere you need it.
I have used similar thing in my app, where I had a "global" kind of object which was saving different configs etc, and then I was using that in the components which needed that data.
Here is also some more info about component communication in React.
A plain-old JavaScript module. Encapsulate the data to be shared as a function/method, and import it into any React components that need
to access it. The seems like the simplest approach, but I have the
feeling that when writing a ReactJS app everything should be defined
as a component, rather than JavaScript classes/functions.
I disagree, React is a library that helps to create user interfaces through components but it doesn't mean that (services, translations, configuration data) have to be built into components, on the other hand, it's actually discouraged you shouldn't couple your services/configuration to a library
you should limit the scope of React to what it is used for. So using plain-old JavaScript modules feels the right way to implement a simple react app.
Redux seems to be recommended approach for sharing-state within large
apps, but this feels like overkill for smaller projects
I think it depends on the complexity of the app rather the size, here is where you should think on, how does your app will evolve or if redux isn't what you really need to remove all this data-sharing dependency within React.
Something else?
The react context (discourage)
The observable pattern
https://www.npmjs.com/package/react-observable-subscribe
I think you should go for the redux solution. It sounds like an over kill but it has an added advantage of having a global state object, therefore you can easily choose when to re-render your app when data is shared across compoents.
you can use context in react :
https://reactjs.org/docs/context.html
or you can create a global variable in window object too
the other way is to use observer design pattern plagin and use it.
mobX or other stateManagement component is good too beside redux

How to avoid global variables when different functions need data from database call. (JS)

I'll try to explain the title (-;
I'm making an app. It calls a database in the backend.
The app also collects user information on different screens. They need to be combined with the data from the backend in different ways and give an output to the user.
I want to call the db once and not from every function. So now, on the 'init' I define a lot of global variables.
I know* that all this global variable stuff is no a good idea. But what is?
*)have read
This is where a JavaScript library may serve you well. Frameworks such as React allow you to set up ways of handling different models such as the user model you describe and making it easier to work with each model throughout the app
Thanks #finalfreq' i see there are a lot of frameworks. And also, it will take a while to learn and work with them. But i'm glad i don't have to search anymore within Javascript itself. (-;

Creating Cycle.js reusable modules

Let's imagine, in a OO world, I want to build a Torrent object which listens to the network and lets me interact with it. It would inherit an EventEmitter and would look something like this:
var torrent = new Torrent(opts)
torrent.on('ready', cb) // add torrent to the UI
torrent.on('metadata', cb) // update data in the UI
and I can also make it do things:
torrent.stop()
torrent.resume()
Then of course if I want to do delete the torrent from memory I can call torrent.destroy().
The cool thing about this OO approach is that I can easily package this functionality in its own npm module, test the hell out of, and give users a nice clean reusable API.
My question is, how do I achieve this with Cycle.js apps?
If I create a driver it's unclear how I would go about creating many torrents and having their own independent listeners. Also consider I'd like to package functionality in a way that others get to easily reuse it in other Cycle.js apps.
It seems to me that you are trying to solve a problem thinking about it as you would write "imperative code".
I think creating Torrent instances with their own listeners is not something you should be using in cycle components.
I would go about it differently - creating Torrent module and figuring out what would be its sources and sinks. If this module should be reusable and published, you can create it as a function that would receive streams as arguments. Maybe something similar to TodoMVC Task component (which is then used in its parent component).
Since this module can be created as a pure function, testing it should be at least just as easy.
This implementation of course depends on your requirements but communication with the module would then be done only with streams and since it would be declarative there would be no need for methods like stop() and destroyed() which you would call from elsewhere.
How do I test it?
In cycle.js you'd write a component with intent model and view functions.
You'd test intent(), for given input Streams, produces Streams of actions that you want. For models, you'd test that given http and action streams, you get the state you want, and for view, you test that given a state you get the VDom you want.
One tricky bit with cycle.js is that since it passes functions around, normal JavaScript objects that use the 'this' keyword are not worth the trouble due to 'this' context problems. If you are working with cycle.js and you think you might write a JS class for use with Isolate, Onionify, or Collections most likely, you are going in the wrong direction. See MDN docs about 'this'
how I would go about creating many torrents
The Cycle.js people have several ways to deal with groups of things like this.
This ticket describes some things that might work for that:
Wrap subapp in Web Component
Stanga and similars.
Cycle Collections
Cycle Onionify

Categories

Resources