I'm studying ReactJS and I'm having doubts with the use of Hook ( useState ). I want to create a javascript function that stores the value in ( useState ) the parameter is being received in the function. I called the function and passed the string I want to keep. And my wish is to display the value stored in ( useState ) on my HTML page.
My code [ index.js ]:
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
My code [ App.js ]:
import React, { useState } from 'react';
const App = () => {
const [name, saveName] = useState(false);
const updateName = date => saveName(date);
updateName('David');
return (
<h1>{ name }</h1>
);
};
export default App;
The error:
×
Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
▶ 17 stack frames were collapsed.
Module.<anonymous>
C:/Users/StarWars/Desktop/React-Projects/portfolio/src/index.js:5
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
> 5 | ReactDOM.render(<App />, document.getElementById('root'));
6 |
View compiled
Module../src/index.js
http://localhost:3000/static/js/main.chunk.js:231:30
__webpack_require__
C:/Users/StarWars/Desktop/React-Projects/portfolio/webpack/bootstrap:851
848 |
849 | __webpack_require__.$Refresh$.init();
850 | try {
> 851 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 852 | } finally {
853 | __webpack_require__.$Refresh$.cleanup(moduleId);
854 | }
View compiled
fn
C:/Users/StarWars/Desktop/React-Projects/portfolio/webpack/bootstrap:150
147 | );
148 | hotCurrentParents = [];
149 | }
> 150 | return __webpack_require__(request);
| ^ 151 | };
152 | var ObjectFactory = function ObjectFactory(name) {
153 | return {
View compiled
1
http://localhost:3000/static/js/main.chunk.js:245:18
__webpack_require__
C:/Users/StarWars/Desktop/React-Projects/portfolio/webpack/bootstrap:851
848 |
849 | __webpack_require__.$Refresh$.init();
850 | try {
> 851 | modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
| ^ 852 | } finally {
853 | __webpack_require__.$Refresh$.cleanup(moduleId);
854 | }
View compiled
checkDeferredModules
C:/Users/StarWars/Desktop/React-Projects/portfolio/webpack/bootstrap:45
42 | }
43 | if(fulfilled) {
44 | deferredModules.splice(i--, 1);
> 45 | result = __webpack_require__(__webpack_require__.s = deferredModule[0]);
| ^ 46 | }
47 | }
48 |
View compiled
Array.webpackJsonpCallback [as push]
C:/Users/StarWars/Desktop/React-Projects/portfolio/webpack/bootstrap:32
29 | deferredModules.push.apply(deferredModules, executeModules || []);
30 |
31 | // run deferred modules when all chunks ready
> 32 | return checkDeferredModules();
| ^ 33 | };
34 | function checkDeferredModules() {
35 | var result;
View compiled
(anonymous function)
http://localhost:3000/static/js/main.chunk.js:1:71
Thanks
CodePudding user response:
Every call to setState
tells React to update the state and re-render the component, so your component reads like this:
const [name, saveName] = useState(false);
-- initialize state tofalse
const updateName = date => saveName(date);
-- defineupdateName
which, updates stateupdateName('David');
-- Call asetState
, which re-renders the component; go back to step 1
... over and over until it errors out
If you want to initialize the value of your name
state, pass the value you want to initialize it to to useState
. I'd also recommend sticking with the conventions identified in the docs for the state hook to keep your component idiomatic and easily understood to other React devs, so I'd rewrite your component as:
const App = () => {
const [name, setName] = useState('David');
return (
<h1>{ name }</h1>
);
};
Of course this is a contrived example, because you're not actually leveraging state to its full potential as it was intended, but neither were you in the original code.
CodePudding user response:
You can't put a function call here because updateName
trigger a re-render of the component.
You can for example call that function on an event or trigger in the useEffect hook.
Since with updateName
you're basically calling the saveName
function without adding any other logic you can use directly saveName
Another thing: if you're using a string don't initialize the name
with a boolean value
For example you can do:
import React, { useState } from 'react';
const App = () => {
const [name, saveName] = useState('');
return (
<div>
<div onClick={() => saveName('David')}>Set the name</div>
<h1>{ name }</h1>
</div>
);
};
export default App;