I am curious to know which one perform better. Two of the example run correctly without warning, but is it acceptable to declare mutable variable in react without useState ? (Example using react query for data fetching)
Ex 1 :
let flexibleName = ""
const { data, status } = useQuery("users", fetchUsers)
if(data) flexibleName = "TEST DATA"
return <div>{flexibleName}</div>
Ex 2 :
const [flexibleName, setFlexibleName] = useState("")
const { data, status } = useQuery("users", fetchUsers)
useEffect(()=>{
if(!data) return
setFlexibleName("TEST DATA")
},[data])
return <div>{flexibleName}</div>
Is it acceptable to declare mutable variable in react without
useState
?
Yes, it's ok to do so. flexibleName
appears to be derived state (derived from data
), and as such doesn't belong in React state. Use the first example.
const { data, status } = useQuery("users", fetchUsers);
const flexibleName = data ? "TEST DATA" : "";
return <div>{flexibleName}</div>;
If you need to you can memoize the flexibleName
value with the useMemo
hook.
const { data, status } = useQuery("users", fetchUsers);
const flexibleName = useMemo(() => {
return data ? "TEST DATA" : "";
}, [data]);
return <div>{flexibleName}</div>;
See Identify the Minimal (but complete) Representation of UI State for more details regarding derived state.
Ask three questions about each piece of data:
- Is it passed in from a parent via props? If so, it probably isn’t state.
- Does it remain unchanged over time? If so, it probably isn’t state.
- Can you compute it based on any other state or props in your component? If so, it isn’t state.
Note the emphasis is mine.
Computing the derived state also avoids the unnecessary rerenders just to update some state for display. Or another way to think about it is that the useMemo
hook is like combining the useState
and useEffect
hooks to update and memoize a value without triggering the additional rerender.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With