Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to declare variable without useState in functional components ? React Hooks

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>
like image 345
Lheanarda Avatar asked Oct 13 '25 05:10

Lheanarda


1 Answers

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:

  1. Is it passed in from a parent via props? If so, it probably isn’t state.
  2. Does it remain unchanged over time? If so, it probably isn’t state.
  3. 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.

like image 117
Drew Reese Avatar answered Oct 14 '25 21:10

Drew Reese