EN
React - optimal way to create state
3
points
In this article, we would like to show you optimal way to create state in React.
When creating initial state in a component needs some complex operations we should pass an arrow function as React.useState
argument instead of just passing an object.
This approach prevents from doing complex operations every time component re-renders with the same value.
In our case we prevent parsing jsonOrData
with every App
re-render just by passing an arrow function as useState
argument.
Good approach:
const [data, setData] = React.useState(() => createData(jsonOrData));
Bad approach:
const [data, setData] = React.useState(createData(jsonOrData));
Runnable example:
// ONLINE-RUNNER:browser;
// import React from 'react';
// import ReactDOM from 'react-dom';
const createData = (jsonOrData) => {
if (typeof jsonOrData === 'string') {
return JSON.parse(jsonOrData);
}
return jsonOrData;
};
const User = ({jsonOrData}) => {
// When state creation is heavy we sould use useState(() => ...)
const [data, setData] = React.useState(() => createData(jsonOrData));
// When state change is heavy we sould use useEffect(() => ..., [...])
React.useEffect(() => createData(jsonOrData), [jsonOrData]);
return (
<div>
{data.name} {data.age}
</div>
);
};
const App = () => {
const user = {
name: 'John',
age: 25,
// other properties here...
};
return (
<div>
<User jsonOrData={user} />
</div>
);
};
const root = document.querySelector('#root');
ReactDOM.render(<App />, root );