gkeenley
gkeenley

Reputation: 7358

React Native: how do you include constructor with functional components?

Up until now in React Native, I've always created components like this

class <name> extends Component {
  constructor(props) {...}
  componentDidMount() {...}
  render() {
    return (
      ...
    )
  }
}

I see that in newer documentation they create components like this:

function <name> {
  return (
    ...
  )
}

If I'm using the second syntax, how do I add constructor and componentDidMount?

Upvotes: 0

Views: 41

Answers (1)

wentjun
wentjun

Reputation: 42516

As mentioned on react's documentation for react hook, you can make use of the useEffect hook and pass in an empty array as the dependency array,

If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run.

useEffect(() => {
  // insert logic for componentDidMount here
}, []);

Upvotes: 1

Related Questions