Set state with same value using hooks will cause a rerender?

It won’t re-render the component if you call setState with the same value.

Try this out:

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

const foo = { foo: 'bar' };

export default ({ name }) => {
  const [state, setState] = useState(foo);
  console.log("rendered!");
  useEffect(() => {
    setState(foo);
    console.log("state reset!");
  });

  const handleClick = () => {
    console.log("handleClick!");
    setState(foo);
    // setState({ ...foo, bar : 'baz' });
  }

  return (<div>
  <h1>Hello {name}!</h1>
  <button onClick={handleClick}>Click Me</button>
  </div>);
};

You’ll notice that even when the button is clicked since the value has not changed. it’s not re-rendering the Component. If you change the argument that you call setState with, it will re-render the component.


Here’s a Code Sample for your ref.

Try commenting the first setState and un-commenting the second one inside the handleClick method to see the difference.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)