Why useState calls function twice? [duplicate] - javascript

My React Component is rendering twice. So, I decided to do a line-by-line debug, and the problem is here:
if ( workInProgress.mode & StrictMode) {
instance.render();
}
React-dom.development.js
Is it because of the strict mode? Can I disable it? What is Strict Mode? Do I need it?

StrictMode renders components twice (on dev but not production) in order to detect any problems with your code and warn you about them (which can be quite useful).
If you have StrictMode enabled in your app but don't remember enabling it, it might be because you used create-react-app or similar to create your app initially, which automatically enables StrictMode by default.
For example, you might find that your {app} is wrapped by <React.StrictMode> in your index.js:
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root')
);
If so, you can disable StrictMode by removing the <React.StrictMode> tag:
ReactDOM.render(
{app}
document.getElementById('root')
);

Yes you have to remove Strict mode as
Strict mode can't automatically detect side effects for you, but it can help you spot them by making them a little more deterministic. This is done by intentionally double-invoking the following functions: Class component constructor , render , and shouldComponentUpdate methods.
Source: React Docs: Strict Mode

For Next.js user here like my-self,
strict mode is also enabled by default and causes this issue.
You can disable it in this way
// next.config.js
module.exports = {
reactStrictMode: false,
}

It seems the component renders twice, but the first rendered component is not unmounted? At least that is the behaviour I'm seeing with React 17, might a bug in my code of course

In a React app with StrictMode:
If you are seeing dual console logs like this:
And if you know that StrictMode helps you optimize your app in some way
And you don't want to disable StrictMode entirely
Then:
The React Developer Tools Chrome Extension offers an option to Hide logs during second render in Strict Mode. To enable that:
Install the extension.
In your Chrome Developer Tools window, a new tab called Components is created. Click on it.
Then click the gear icon inside the components tab.
Then select the Debugging tab, and check the option to Hide logs during second render in Strict Mode.
You will no more see the dual logs in the console.

if you are using nextjs and you want to disable strict mode go to your next.config.js file and set reactStrictMode to false
module.exports = {
reactStrictMode: false,
};
but strict mode is recommended for development once you check if the double mount is caused by stric mode it's preferable to enable it

Related

importing ConnectButton from web3uikit gives Error: Invalid hook call. Hooks can only be called inside of the body of a function component

I am using nextjs along with tailwind css and a bunch of other libraries like web3uikit.
the app work totally fine but as soon as I import ConnectButton from web3uikit and use it in the sidebar component, it gives me the following error:
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
Here's the link to the github repo, just cloning and install the dependencies would help you in setting up the project and then npm run dev.
Link: https://github.com/oneknucklehead/marketplace-web3
I believe it is a server-side rendering issue! A screenshot of how I got the <ConnectButton /> to render in a nextjs application is below:
Implementing the ConnectButton Component Screenshot
When the error popped up saying I had an invalid hook call, I closed the error box and the button was rendered in and when I click on it, it showed the web3Modal with the proper sign-in options. I thought that maybe it was a server-side issue
So I fixed it by using a useState hook with a boolean value as seen in the screenshot. It is false by default but will only become true when the component loads in(used a useEffect hook to implement) and I take advantage of that via conditional rendering which is also shown in the screenshot. Once I did that, I haven't encountered the issue at all! Hope this helps!
Go to node_modules -> web3uikit-> node_modules and delete the react folder under it.
web3uikit node module has a version of react pre-installed with it. Apparently, that's causing errors. Now, why does deleting the folder fix the error? Honestly, I don't know, but it removed the error. This answer is from someone named David MacDonald.

React Native - Expo - How to check if Dark mode is enabled?

I have read in the Expo/RN documentation, that for getting the system color (dark/light) we should use this API from react native.
So, I have decided to create my custom hook
import { Appearance } from "react-native";
export default function useIsDarkModeEnabled() {
return Appearance.getColorScheme() === "dark";
}
But for some reason, it is always returning me false. I am testing on iOS 14, with dark theme enabled.
Any ideas?
Whenever I check the current appearance of the device I use the useColorScheme() function, not getColorScheme().
You can use Context to persist it throughout the application, or put it at the root of your app and pass it down to your components as props (not the best). To persist the theme, you can use AsyncStorage to store the last state of the appearance.
Then whenever the application opens, it will pull that last state unless the device has changed its appearance since then.

Why resolve function executed two times in Promise? [duplicate]

I heard that strict mode helps to write React code in best practices way by throwing warnings for life cycle methods removal. I read about it from this article on Medium.
Is my understanding correct? How effective is strict mode? Is it only for unsafe life cycle methods? If not can I use this feature in functional components?
import { StrictMode } from "react";
class Test extends Component{
render(
<StrictMode>
//Some other child component which has all lifecycle methods implemented in it
</StrictMode>
);
}
React's StrictMode is sort of a helper component that will help you write better React components, you can wrap a set of components with <StrictMode /> and it'll basically:
Verify that the components inside are following some of the recommended practices and warn you if not in the console.
Verify the deprecated methods are not being used, and if they're used strict mode will warn you in the console.
Help you prevent some side effects by identifying potential risks.
As the documentation says, strict mode is development oriented so you don't need to worry about it impacting on your production build.
I've found it especially useful to implement strict mode when I'm working on new code bases and I want to see what kind of code/components I'm facing. Also if you're on bug hunting mode, sometimes it's a good idea to wrap with <StrictMode /> the components/blocks of code you think might be the source of the problem.
So yeah, you're in the correct path to understanding strict mode, keep it up, I think it's one of those things you understand better when you play with them, so go ahead and have some fun.
Warning: StrictMode will render the components twice only on the development
mode not production.
For instance, if you're using getDerivedStateFromProps method like so:
static getDerivedStateFromProps(nextProps, prevState){// it will call twice
if(prevState.name !== nextProps.name){
console.log(`PrevState: ${prevState.name} + nextProps: ${nextProps.name}`)
return { name: nextProps.name }
}
return {}
}
The getDerivedStateFromProps method will call twice.
Just to let you know this is not a problem, it's just because you're wrapping your main component with <StrictMode> in the index.js file.
StrictMode renders components twice in order to detect any problems with your code and warn you about them.
In short, StrictMode helps to identify unsafe, legacy, or deprecated APIs/lifecycles. It's used for highlighting possible problems. Since it's a developer tool, it runs only in development mode. It renders every component inside the web app twice in order to identify and detect any problems in the app and show warning messages.
StrictMode is a tool for highlighting potential problems in an application. Like Fragment, StrictMode does not render any visible UI. It activates additional checks and warnings for its descendants.

Gatsby application does not render on edge, ie. [ HTML1300, SCRIPT5009: SCRIPT5009: 'PerformanceObserver' is not defined ]

I ran into a problem opening the website I made using gatsby.js.
The problem is only on browsers: ie, edge (I tested Firefox, chrome, ie, edge)
First, the browser shows the whole rendered page then it destroys the layout for some reason.
The exception in the console is:
1-time: HTML1300,
2-times: ReferenceError: 'PerformanceObserver' is not defined,
1-time: SCRIPT5009: SCRIPT5009: 'PerformanceObserver' is not defined
Also any tips on how to update this project because it shows me some warnings in local production. I looked in the gatsby docs for a while but I cannot find anything. Sorry for the dumb questions but kinda a newbie at React, gatsby...😅
Errors:
React-Hot-Loader: react-🔥-dom patch is not detected. React 16.6+ features may not work.
in AppContainer (created by HotExportedIndexPage)
in HotExportedIndexPage (created by PageRenderer)
in PageRenderer (at json-store.js:93)
in JSONStore (at root.js:51)
in RouteHandler (at root.js:73)
in EnsureResources (at root.js:61)
in LocationHandler (at root.js:119)
in LocationProvider (created by Context.Consumer)
in Context.Consumer (created by Location)
in Location (at root.js:118)
in Root (at root.js:127) backend.js:6:2315
Warning: componentWillMount has been renamed, and is not recommended
for use. See react-unsafe-component-lifecycles for
details.
Move code with side effects to componentDidMount, and set initial state in the constructor.
Rename componentWillMount to UNSAFE_componentWillMount to suppress this warning in non-strict mode. In React 17.x, only the UNSAFE_ name
will work. To rename all deprecated lifecycles to their new names, you
can run npx react-codemod rename-unsafe-lifecycles in your project
source folder. Preziranje nepodprtih entryTypes: paint.
gatsby-browser.js:15
Please update the following components: SideEffect(NullComponent) backend.js:6:2315
Any insight or help into this mystery is very appreciated 😊
Here is the link to my google drive folder where I pasted gatsby config files. If you need any other info about the page I will gladly provide the necessary information.
With refer to this article, we can see that the PerformanceObserver doesn't support IE and Edge browser.
React-Hot-Loader: react-🔥-dom patch is not detected.
About this issue, please check the webpack config, perhaps you need to use "#hot-loader/react-dom", instead of "react-dom". more detail information, please check this thread and this issue.
Besides, I suggest you check the package.json file and check the Gatsby Browser support.

Object equality issue after babelification in Next.js

I have a React project build with Next.js. I added the React Simple Dropdown module and am just using the basic sample author provides. All works fine. Now I would like to copy the 3 dropdown files from the module and modify them. So I copied the src files to my components directory and changed my line in my code from:
import Dropdown, { DropdownTrigger, DropdownContent } from 'react-simple-dropdown'
to:
import Dropdown, { DropdownTrigger, DropdownContent } from './Dropdown/Dropdown'
This causes this line to no longer work: if (child.type === DropdownTrigger).
Inspecting the child.type I see a difference (top is my code):
It seems that my Next.js webpack is handling things differently than whatever tool the author use to babelify the original code. I am able to handle the match in other ways but would like to understand what is happening. It seems related so some default export but I am not clear why things are different and what Babel setting handles this.
Evidently class comparison doesn't work with React Hot Loader in dev mode. Known issue with no fix at the moment. So using item.type.displayNane === 'DropdownTrigger' would be a workaround.

Categories