When a component re-renders, are all variables inside it re-defined?

Asked
Active3 hr before
Viewed126 times

8 Answers

definedvariablesinsidecomponent
90%

and with this Class based example, all of the instance methods will be re-defined on every render? or only stuff inside render() method?,In the functional component, consider the function is the render function. So it gets executed entirely like any normal function (no black magic here) on re-render. So yes, anything defined within that scope will be redefined.,Making statements based on opinion; back them up with references or personal experience.

Pretag
 Pretag team - issue, fix, solve, resolve
88%

Let’s extend the TickerComponent to support a ‘theme’ prop. Its parent component(‘App’) holds the theme value in a state and passes it down to children via props.,4th group: Now the theme value is changed in the parent, both the parent (App) component and its children (ticker components) were re-rendered.,useState hook is the primary building block which enables functional components to hold state between re-renders.

Let’s understand the workings of useState with an example. We will implement the Ticker component as per the above sketch. The active ticker which is shown on the UI is stored in a local state using useState hook. Here is the relevant portion of the component (full code here).

const [ticker, setTicker] = useState("AAPL");...
const onChange = event => {
   setTicker(event.target.value);
}...
load more v
72%

It then runs the function for the component to render the component with the updated states and refs. This re-rendering will also re-initialize variables to hold their initial values as defined in the component since they are not tracked.,Initially, the component initializes all variables to the default values, also stores all the state and refs to a unique store as defined by the React algorithm.,The result after running this code and placing a mouse on the title updates the variable internally but does not cause a re-render, meanwhile, a re-render is triggered by the parent component which re-initializes the variable to the initial state of false as defined in the component. Interesting!

function Card (props) {
  let toggled = false;
  
  const handleToggleBody = () => {
    toggled = true;
    console.log(toggled);
  };

  useEffect(() => {
    console.log(“Component rendered, the value of toggled is:“, toggled);
  }, [props.title]);

  return (
    <section className=“card”>
      <h3 className=“card__title” onMouseMove={handleToggleBody}>
        {props.title}
      </h3>

      {toggled && <article className=“card__body”>{props.body}</article>}
    </section>
  );
}

// Renders the application
function App () {
  
  const [cardDetails, setCardDetails] = useState({
    title: “Something”,
    body: “uniquely done”,
  });

  useEffect(() => {
    setTimeout(() => {
      setCardDetails({
        title: “We”,
        body: “have updated something nice”,
      });
    }, 5000); // Force an update after 5s
  }, []);

  return (
    <div>
      <Card title={cardDetails.title} body={cardDetails.body} />
    </div>
  );
}
load more v
65%

All I need to do in the Greeting component is wrap it another function called React.memo().,The second React component is the App component, and it uses the Greeting component.,React functional components do not have lifecycle methods.

React.memo(YourComponent);
load more v
75%

Conceptually, you can think of refs as similar to instance variables in a class. Unless you’re doing lazy initialization, avoid setting refs during rendering — this can lead to surprising behavior. Instead, typically you want to modify refs in event handlers and effects.,As a last resort, if you want something like this in a class, you can use a ref to hold a mutable variable. Then you can write and read to it. For example:,Is there something like instance variables?

function Example() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}
load more v
40%

Lets distill our question down into something we could search Google with. If you think about it, what we’re really trying to find out here is how we can tell JSX to render any Javascript expression (essentially anything that produces a value when interpreted). A quick search for “JSX render javascript expression” yields us the answer!,Lets start with the code from our last post:, Common Code Patterns Finish reading about rendering variables and move on to the next section!

var Hello = React.createClass({
    render: function() {
        return <div>Hello, haters!</div>;
    }
});
load more v
22%

The values in the fields will be used to determine if your component needs to re-render,mapStateToProps Functions Should Be Fast,mapStateToProps should be defined as a function:

function mapStateToProps(state, ownProps ? )
load more v
60%

Open the demo, then expand the console. You will see that React renders <MemoizedMovie> just once, while <Movie> re-renders every time.,Let’s see the memoization in action. The functional component Movie is wrapped in React.memo():,Let’s use the memoized component MemoizedMovie inside MovieViewsRealtime to prevent useless re-renderings:

export function Movie({ title, releaseDate }) {
  return (
    <div>
      <div>Movie title: {title}</div>
      <div>Release date: {releaseDate}</div>
    </div>
  );
}

export const MemoizedMovie = React.memo(Movie);
load more v

Other "defined-variables" queries related to "When a component re-renders, are all variables inside it re-defined?"