Buzz
Buzz

Reputation: 59

How to call function before render in hook react native?

Use effect only run after render. Which method will only called one time and run before the initial render in function hook ? I cant use componentWillMount because it must be inside class component and hook must inside function.

Upvotes: 1

Views: 5773

Answers (2)

Vočko
Vočko

Reputation: 2986

A simple answer is you can't. You can either solve it by returning null, Fragment or some sort of replacement (spinner etc.) until the data are loaded (that means at least for the first render) or load the data in the parent and only render the child component when data are in (and pass them down through props).

const [data, setData] = useState(null);

useEffect(() => {

    // Load data here

}, []);

return data ? null : <>{data}</>

Upvotes: 0

Abdul Basit Mangat
Abdul Basit Mangat

Reputation: 1180

Actually hooks are itself functions (They let you use state and other React features)without writing a class. And in respective they don't have any component life methods.like componentWillMount() etc.

So one solution is to use hooks as a separate component in your class.And then in your js class you have access to all lifecycle methods.There is a method shouldComponentUpdate(state, props) It takes props and states and you can compare if you want to re-render screen or not.It will call right before rendering.If returned "true" screen will render again else not.

shouldComponentUpdate(nextProps, nextState) {
if (nextProps === this.props && nextState === this.state)
  return false
else
  return true

}

Below is the example for hooks to use in render method of class

 import React, { useState } from 'react';
 const ExampleHook = props => {
   return (
      <View>
        <Text>Hello i am from hook</Text>
      </View>
    );
 }
 export default ExampleHook

Now you have to import this hook in your other js file. and you can use this in render method of that class.You have to decide based on decision from shouldComponentUpdate() function.

Upvotes: 1

Related Questions