2

I am new to React hooks. So, I wanted to implement componentWillReceiveProps with React hooks. I used React.useEffect() like so:

React.useEffect(() => {
    console.log(props.authLoginSuccess);  // initially called every time, the component renders
  }, [props.authLoginSuccess]);


return ( //JSX...)

onst mapStateToProps = (state: any): StateProps => {
  return {
    authLoginSuccess: selectAuthLoginSuccess(state) //used selector to select authLoginSuccess
  };
};
export default connect(
  mapStateToProps,
  // mapDispatchToProps
  { authLogin, toggleLoadingStatus } 
)(Auth);


The problem is, useEffect is called each time the component renders initially, which I don't want. I only want it to render, when "props.authLoginSuccess" changes.

3
  • What data structure is props.authLoginSuccess? Commented Jul 23, 2019 at 18:06
  • ...another wild guess: your component may be remounted by its parent(or alongside parent). you may check that by adding useEffect(() => { console.log('mounted!'); return () => console.log('unmounted');}, []) Commented Jul 23, 2019 at 18:22
  • @go_diego, props.authLoginSuccess is a boolean. Commented Jul 24, 2019 at 8:17

3 Answers 3

6

Since you want the effect to not run on initial render, you can do that by making use of useRef

const initialRender = useRef(true);
React.useEffect(() => {
    if(initialRender.current) {
        initialRender.current = false;
    } else {
        console.log(props.authLoginSuccess);  // initially called every time, the component renders
    }
  }, [props.authLoginSuccess]);
Sign up to request clarification or add additional context in comments.

Comments

1

Wrap it in an if condition like this:

React.useEffect(() => {
  if (props.authLoginSuccess) {
    console.log(props.authLoginSuccess);
  }
}, [props.authLoginSuccess]);

Note that the effect will still run though - both initially and every time props.authLoginSuccess changes (which is okay!).

The if block will prevent running console.log(props.authLoginSuccess) when props.authLoginSuccess is falsy. So if you don't want it running initially i.e. when component mounts, just make sure that props.authLoginSuccess is false initially.

Comments

1

You could add another state that would monitor whether or not the component has been mounted.

const [isMounted, setIsMounted] = React.useState(false);

React.useEffect(() => {
  if (isMounted) {
    console.log(props.authLoginSuccess);
  } else {
    setIsMounted(true);
  }
}, [props.authLoginSuccess]);

That way, it will only execute when the component has been mounted.

1 Comment

This is a workaround and I have tried that too, does not help with my case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.