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 https://medium.com/@baphemot/whats-new-in-react-16-3-d2c9b7b6193b
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With