Skip to content

Instantly share code, notes, and snippets.

@jyydev
Last active June 30, 2021 10:28
Show Gist options
  • Save jyydev/a30eba95fa812c3feca98dbf1a3122ac to your computer and use it in GitHub Desktop.
Save jyydev/a30eba95fa812c3feca98dbf1a3122ac to your computer and use it in GitHub Desktop.
React > component > render twice on useState(), set

React > component > render twice on useState(), setValue()

Problem

React component render twice on useState().

const [value, setValue] = useState('');

Each time value is changed on setValue():

setValue('hello world')

console.log('render')

The component is rendered twice (render appears twice in console).

Solution:

  1. Go to index.js file in src folder.

    • src folder is located in root folder
  2. Remove <React.StrictMode>, </React.StrictMode>, from the code.

Default react code:

ReactDOM.render(
  <React.StrictMode>
    <App />,
  </React.StrictMode>,
  document.getElementById('root')
);

After changes:

ReactDOM.render(
    <App />,
  document.getElementById('root')
);

This will solve the rendering twice problem.

Notes

This is not a bug, but a feature provided by React to catch outdated functions, you can Google if you want to find out more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment