Vitaliy Khudonogov
Vitaliy Khudonogov

Reputation: 96

React useState vs raw variable

For example i have a some data which need to be rendered. Items will be always the same but they are coming from props.

const items = props.data.values.map(value => ({
  id: value.id
  name: value.name,
  rating: Number(value.rating)
}));

return (
  {items.map(item => (
    <div key={item.id}....
  )}
);

May i use useState for items variable like that:

const [items] = useState(data.values.map(value => ({
  id: value.id
  name: value.name,
  rating: Number(value.rating)
})));

Does it's help me to get rid of redundant "mapping" during next rerender or not?

Upvotes: 2

Views: 1757

Answers (2)

Eddie Cooro
Eddie Cooro

Reputation: 1968

No, it doesn't help.
I think it's better to completely get rid of the first map and do whatever you want in the second one. but if you think that is necessary for your app, you could use useMemo hook.
This hook provides you a memoized value that re-calculates only if some parameters change.
For example:

const items = useMemo(() => {
    return data.values.map(...)
}, [data])

This example calculates items only if the value of data changes. otherwise, it returns the memoized version and doesn't re-calculate anything.


But what about useState? it used whenever we have some variable that whenever it changes, we want to re-render our component and show some new contents. for example, we have a Counter that whenever its value changes, we want to re-render component and show the new Value. so we use something like this:

const Counter = (props) => {
    const [value, setValue] = useState(0)
    return (
        <div>
            <p>{value}</p>
            <button onClick={() => setValue(value + 1)}>Increment</button>
            <button onClick={() => setValue(value - 1)}>Decrement</button>
        </div>
    )
}

So whenever we call setValue, the component re-renders and the new value will be shown to the user.

Upvotes: 2

Vladimir Bogomolov
Vladimir Bogomolov

Reputation: 1794

I think what you're looking for is Pure Components. They use shouldComponentUpdate to determine if the component needs to re-render. In your case if the props are the same, the component won't re-render if you use a Pure Component.

Upvotes: 0

Related Questions