Home > database >  What is the definition of first render in react native?
What is the definition of first render in react native?

Time:12-08

I am confused when will the first render happen. I tried following to figure it out.

//login.js
    useEffect(() => {
        console.log('first render');
    }, []);

I have navigation like this: login.js(console.log success)=>home.js=>login.js(console.log fail) Is that because I have navigation history of login.js which make it not first render?

Thanks!

CodePudding user response:

Assuming you're using react-navigation, your intuition is right. In pure React (for the web), useEffect would run again, because the component would have been unmounted when you navigated, and mount again (as if for the first time) when you went back.

However, in react-navigation/native, the component stays mounted in your stack, and will not re-render on navigating back to it. However, the "child" would be unmounted when you navigated back. For example, if you navigated from login => home => login => home, home would be unmounted when going back to login. If you had put your useEffect inside home, in this scenario, it would run twice.

This is discussed in their docs here.

CodePudding user response:

React has the ability to both render and re-render its components to the DOM which is efficiently updated through Reacts Virtual Dom [VDOM].

  • Reacts Virtual DOM is the virtual representation of the UI kept in memory which is synced through the react-dom library typically found in the index.js file.

    import ReactDOM from 'react-dom';

React has two stages of rendering

  1. The initial render - This first happens when a component first appears on the screen
  2. The re-render - Defined as any render after the initial render.

There are four reasons a component re-renders itself.

  1. Change in the components state - which is usually the root cause

Can happen by a callback function or useEffect

  1. When a parent or child component re-renders

Re-rending goes down the component tree - Therefore, children do not re-render their parents

  1. Changes in a components context value

When the value of Context Provider changes, all components that use it re-render even if they don't use the changed portion of the data directly

  1. Change in a componeont because of a hook

Everything that happens inside a hook 'belongs to’ the component. State change inside a hook triggers an unpreventable re-render of the containing 'host' component.

  • Related