useeffect react cleanup not working with React Native modal - reactjs

The effect for the modal looks like this:
useEffect(() => {
console.log('mounted')
return () => {
console.log('unounted')
}
}, [])
When I try to call the modal conditionally like this :
modal ? <Suspense fallback={<ActivityIndicator/>}><Modal /></Suspense> : null
the console shows mounted when modal===true but doesn't show unmounted when modal===false.What's going on here?Does functional component cleanups don't work in React Native?Or is there something else happening behind the curtain?

You should use the Modal's visible prop if you want to show the modal conditionally.
Add a state to the modal's father component like this:
const [isModalShown, setIsModalShown] = useState(false)
Then pass the state (isModalShown) to the prop and when you want to show the modal change the state to true (setIsModalShown(true))

Related

How to start animation before component is removed in React?

I would like to know how do I trigger an animation before removing a functional React component.
I am using the npm package to manage animations via JS. So I just need to call the function. For example function animate.
import React from "react";
useEffect(() => {
function animateStart() {
console.log('AnimateStart')
}
},[]);
export default function () {
return(
<div className={'component'}/>
)
}
This is how I am triggering the animation when the component appears. I would like to somehow catch the removal and postpone it for the duration of the animation.
At the moment I'm calling the delete animation from the parent component. This forces me to store the animateExit function in another component. It is not comfortable :(
Try this:
useEffect(() => {
function animateStart() {
console.log('AnimateStart')
}
return () => {/* whatever you want to do, it will be called everytime when this component is unmounted*/}
},[]);

How do I call useEffect when the trigger is in another component?

I am trying to fetch data in a functional React component using useEffect (since the function is asynchronous) and I compute and return the data in h2 tags that was fetched in this component. However, I want to fetch the data when in another component (App.js) I hit the enter key. I have an enter key handler which calls a useState which I believe should re-render the component but since the useEffect is in another component, I am not getting the calling of the useEffect as I intend. What is the best method to press the Enter key and have useEffect in another component run?
function handleKeyDown(event){
if(event.key === 'Enter'){
//this setHeadingText is a useState variable which should re-render in App.js
setHeadingText(name);
}
It sounds like your useEffect is specifying an empty dependency array (instructing to run only once):
useEffect(() => {
//fetch some data
}, []); // This empty array ensures it only runs 1 time
Have a look at this section in the docs: https://reactjs.org/docs/hooks-effect.html#tip-optimizing-performance-by-skipping-effects
If your second component has access to your headingText state, try specifying your headingText as a dependency to the useEffect, and any changes to it should trigger your useEffect
useEffect(() => {
//fetch some data
}, [headingText]); // Only re-run the effect if headingText changes
Alternatively, remove the dependency array from your useEffect.
Note: this will cause the useEffect to run on every re-render
useEffect(() => {
//fetch some data
}); // run every time the component re-renders
Now that I have understood properly, I think this is the solution you wished for:
The headingText value that is being updated in your App.jsx component should be passed down to your Child component with the help of props. So use <Child headingText={headingText} /> while loading the Child component in your App.jsx.
Inside your Child component, receive the value like this function Child(props) or function Child({ headingText }) if you have more values to pass, prefer props.
Now you can easily access the changes in value made in your App component inside your Child component with the help of props.headingText or headingText respective to the way you defined your Child in point 2.
To re-render your Child component, you will now use the useEffect hook with its dependency set to headingText, like:
React.useEffect(() =>
{
// Code for refetching
}
, [headingText]); // or props.headingText if your Child component uses (props)
For example: CodeSandbox
Hope that helps you!
you can make a conditional rendering with the other component, so it get rendered only if you press Enter which would invoke an event:
//App.js
import {AnotherComponent} from './anothercomponent.js' //assuming the file is in src folder
function RenderOnEnter({pressed}){
if(pressed){
return (
<AnotherComponent/>
)
}
return null
}
function App(){
const [pressed,setPressed] = useState(false)
function handlePressed(e){
if(e.target.key === 'Enter'){
setPressed(True)
}
else{
setPressed(False)
}
}
return(
<div>
<button onClick={(e)=>handlePressed(e)}>Click me to obtain data!</button>
<RenderOnPress pressed={pressed}/>
</div>
)
}

Is it possible render something before the component will unmount?

I created a custom Modal. In the component mount I put the className "visible" with a simple opacity: 1.
Since the Modal has a transition, I also want to put a className "gone" with opacity 0 in the unmount of the component.
Is it possibile wait the transition of the close before unmount it and do something like this:
useEffect(() => {
setClassname('visible');
return () => {
setClassname('gone');
setTimeout(()=>{
OK, NOW U CAN UNMOUNT!
), 200 // time of the transition}
}
}, []);
?
I think React Transition Group can help you. https://reactcommunity.org/react-transition-group/
You should not remove class in unmount, just do this logic in parent component, using React Transition Group. You can find an example
of transition here https://reactcommunity.org/react-transition-group/transition

Can't perform a React State update on unMounted child component?

Am getting this warning:
Can't perform a React state update on unmounted component. This is a no-op...
It results from a child component and I can't figure out how to make it go away.
Please note that I have read many other posts about why this happens, and understand the basic issue. However, most solutions suggest cancelling subscriptions in a componentWillUnmount style function (I'm using react hooks)
I don't know if this points to some larger fundamental misunderstanding I have of React,but here is essentially what i have:
import React, { useEffect, useRef } from 'react';
import Picker from 'emoji-picker-react';
const MyTextarea = (props) => {
const onClick = (event, emojiObject) => {
//do stuff...
}
const isMountedRef = useRef(true);
useEffect(() => {
isMountedRef.current = true;
});
useEffect(() => {
return () => {
console.log('will unmount');
isMountedRef.current = false;
}
});
return (
<div>
<textarea></textarea>
{ isMountedRef.current ? (
<Picker onEmojiClick={onClick}/>
):null
}
</div>
);
};
export default MyTextarea;
(tl;dr) Please note:
MyTextarea component has a parent component which is only rendered on a certain route.
Theres also a Menu component that once clicked, changes the route and depending on the situation will either show MyTextarea's parent component or show another component.
This warning happens once I click the Menu to switch off MyTextarea's parent component.
More Context
Other answers on StackOverflow suggest making changes to prevent state updates when a component isn't mounted. In my situation, I cannot do that because I didn't design the Picker component (rendered by MyTextarea). The Warning originates from this <Picker onEmojiClick={onClick}> line but I wouldn't want to modify this off-the-shelf component.
That's explains my attempt to either render the component or not based on the isMountedRef. However this doesn't work either. What happens is the component is either rendered if i set useRef(true), or it's never rendered at all if i set useRef(null) as many have suggested.
I'm not exactly sure what your problem actually is (is it that you can't get rid of the warning or that the <Picker> is either always rendering or never is), but I'll try to address all the problems I see.
Firstly, you shouldn't need to conditionally render the <Picker> depending on whether MyTextArea is mounted or not. Since components only render after mounting, the <Picker> will never render if the component it's in hasn't mounted.
That being said, if you still want to keep track of when the component is mounted, I'd suggest not using hooks, and using componentDidMount and componentWillUnmount with setState() instead. Not only will this make it easier to understand your component's lifecycle, but there are also some problems with the way you're using hooks.
Right now, your useRef(true) will set isMountedRef.current to true when the component is initialized, so it will be true even before its mounted. useRef() is not the same as componentDidMount().
Using 'useEffect()' to switch isMountedRef.current to true when the component is mounted won't work either. While it will fire when the component is mounted, useEffect() is for side effects, not state updates, so it doesn't trigger a re-render, which is why the component never renders when you set useRef(null).
Also, your useEffect() hook will fire every time your component updates, not just when it mounts, and your clean up function (the function being returned) will also fire on every update, not just when it unmounts. So on every update, isMountedRef.current will switch from true to false and back to true. However, none of this matters because the component won't re-render anyways (as explained above).
If you really do need to use useEffect() then you should combine it into one function and use it to update state so that it triggers a re-render:
const [isMounted, setIsMounted] = useState(false); // Create state variables
useEffect(() => {
setIsMounted(true); // The effect and clean up are in one function
return () => {
console.log('will unmount');
setIsMounted(false);
}
}, [] // This prevents firing on every update, w/o it you'll get an infinite loop
);
Lastly, from the code you shared, your component couldn't be causing the warning because there are no state updates anywhere in your code. You should check the picker's repo for issues.
Edit: Seems the warning is caused by your Picker package and there's already an issue for it https://github.com/ealush/emoji-picker-react/issues/142

How do I force a child component to rerender when given new props values?

I have tried this pattern.
ParentComponent
...
render(
return <ChildComponent newProps="newPropsValue />)
ChildComponent
...
ComponentWillReceiveProps{
this.setState({"propsKey": "newPropsValue"})
}
As far as I understand the initial component rendering is triggered by the props change, and as setState is asynchronous (for some reason), the rendering with the new state update is not done on the first pass.
However what I don't understand is why when it finally decides to update the state, it doesn't rerender the component. I thought state changes that are caused by setState always trigger a rerender.
So in the end I have a component that uselessly rerenders before the state is actually changed, and then does nothing when/if(?) the state is updated. I don't understand this behaviour at all.
setState will trigger componentUdpate -> componentWillUpdate -> render. props change will trigger componentWillReceiveProps before this chain. You can have a look here at this image about React lifecycle. You can see the different how React behave on props and state.
So:
However what I don't understand is why when it finally decides to update the state, it doesn't re-render the component.
Updating state by setState will trigger the render function (re-render). And props also trigger render as well.
Following your code:
componentWillReceiveProps:
this.props.newProps="newPropsValue"
this.state.propsKey="newPropsValue"
render: as above, nothing change.
If any event of childComponent setting propsKey by setState (onClick, onChange ...). Assuming setState({propsKey: "anotherValue"}). Then render will be triggered again with this.state.propsKey="anotherValue and this.props.newProps="newPropsValue"
Now let's update your childComponent's props within parentComponent, assuming newProps="latestPropsValue":
Before componentWillReceiveProps:
this.props.newProps="latestPropsValue"
this.state.propsKey="anotherValue"
After componentWillReceiveProps:
this.props.newProps="latestPropsValue"
this.state.propsKey="latestPropsValue"
How do I force a child component to rerender when given new props values?
If your render is using state then setState inside render. And if you are using props inside render, it also being updated accordingly
I have found a nice solution using key attribute. If we changed key property of a child component or some portion of React Component, it will re-render entirely. It will use when you need to re-render some portion of React Component or re-render a child component depending on props or state. Here is a example. I will re-render the full component.
import React, { useState, useEffect } from "react";
import { PrEditInput } from "./shared";
const BucketInput = ({ bucketPrice = [], handleBucketsUpdate, mood }) => {
const data = Array.isArray(bucketPrice) ? bucketPrice : [];
const [state, setState] = useState(Date.now());
useEffect(() => {
setState(Date.now());
}, [mood, bucketPrice]);
return (
<span key={state}>
{data.map((item) => (
<PrEditInput
key={item.id}
label={item?.bucket?.name}
name={item.bucketId}
defaultValue={item.price}
onChange={handleBucketsUpdate}
mood={mood}
/>
))}
</span>
);
};
export default BucketInput;

Resources