Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

169
Views
React Hooks - Prevent re-render when using prevState

I would like to be able to conditionally set a state based on previous state changes with React Hooks. But if the state remains the same the component shouldn't re-render.

When using class components, I was able to achieve this using:

this.setState(prevState => {
   if(prevState.value !== true) {
     return { value: true }
   }

   return null
})

The code above sets the state to true, only if it's not true. However, if it's already true, the component doesn't re-render. I would like to achieve the same effect with React Hooks.

I know that with React Hooks, I can use the prevState like this:

setValue(prevValue => {
   // some code
   return newValue
})

However, I don't know how to prevent re-render if the state remains the same. Is it possible for me to prevent render after using React Hooks prevState? Thank you for your concern.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Two ways:

  1. Use of pure components using life cycle hooks or useMemo in React Hooks.
  2. shouldComponentUpdate() use the change of state login inside this hook.
about 4 years ago · Juan Pablo Isaza Report

0

Wrap your component by memo

import { useEffect, useState, memo } from "react";

const App = () => {
  const [test, setTest] = useState(false);

  useEffect(() => {
    console.log("re-rendered");
  });

  const setTestToTrue = () => {
    setTest((v) => {
      if (v !== true) return true;
      return v;
    });
  };

  return (
    <div className="App">
      <button onClick={setTestToTrue}>Set test to true</button>
    </div>
  );
};

export default memo(App);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!