Not sure about what you're asking here, but this isn't a new discovery. There is an entire page on the official new React docs dedicated to teaching developers to rely on useEffect only as an "escape hatch" due to its tendency to be a code smell https://react.dev/learn/you-might-not-need-an-effect Also, last year's "Goodbye, useEffect: David Khourshid" conference talk basically outlined most of your discoveries, emphasizing to rely on events + callbacks over effects for cleaner code. Which unsurprisingly, many people took issue with (nobody likes hearing years of react code they've built is wrong) https://www.youtube.com/watch?v=HPoC-k7Rxwo So when should you use an Effect then? Treat is as a synchronization tool. Or more specifically, one you are forced to use to synchronize some piece of React code with some piece of external or third party system that does not offer an event-driven or "react-friendly" way of doing things. Answer from that_90s_guy on reddit.com
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ thoughts on avoiding useeffect/usestate when possible in react?
r/reactjs on Reddit: Thoughts on avoiding useEffect/useState when possible in React?
November 7, 2023 -

obtainable fly bells wise terrific lunchroom light upbeat rhythm wild

This post was mass deleted and anonymized with Redact

๐ŸŒ
Reddit
reddit.com โ€บ r/react โ€บ understanding usestate, useeffect and usecontext in plain english
r/react on Reddit: Understanding useState, useEffect and useContext in Plain English
July 25, 2023 -

I am learning React/Next right now. I have been using useState, useEffect and playing with useContext. Most of the definitions online are a bit too technical for me (my reading comprehension is piss poor, one of my weaknesses when it comes to learning) and add more confusion than just me looking at the code and tinkering with it. So basically...

useState = let's you change data on the fly without a page reload

useEffect = let's you add logic/functions to useState

useContext = let's you expand your data to your entire app and have it persist, as long as page does not reload

Is this an accurate assessment?

Thanks ๐Ÿ™

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ usememo to replace usestate and useeffect
r/reactjs on Reddit: useMemo to replace useState and useEffect
April 28, 2023 -

I have something similar to the following code:

const [value, setValue] = useState(calculateValue(prop))  

function calculateValue(prop) {   
    ... 
}  

useEffect(() => { 
    setValue(calculateValue(prop)) 
}, [prop]}

Is it better to do the following instead, even if the calculateValue is not expensive? Also, setValue is not called anywhere else.

const value = useMemo(() => calculateValue(prop), [prop])

or, in typing this out, I realized maybe this is the best case...

return (
    <div> {calculateValue(prop)} </div>
)

Can anyone shed some light on what the best case would be here?

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ when you're using usestate and useeffect at the same time, does useeffect run first before a hook variable is updated?
r/reactjs on Reddit: When you're using useState and useEffect at the same time, does useEffect run first before a hook variable is updated?
June 23, 2023 -

Hello,So I am learning about useRef() and came across this example in w3schools.com

function App() {
const [inputValue, setInputValue] = useState(""); 
const previousInputValue = useRef("");
useEffect(() => { 
previousInputValue.current = inputValue; }
, [inputValue]);

return ( <> 
<input type="text" value={inputValue} onChange={(e) => setInputValue(e.target.value)} /> 

<h2>Current Value: {inputValue}</h2> 

<h2>Previous Value: {previousInputValue.current}</h2> 

</> );}

Or https://www.w3schools.com/REACT/react_useref.asp (sorry; copy and paste is not working correctly and formatting is getting destroyed on reddit smh)

So, whenever someone changes the value in 'text' input tag (which is "synced" to inputValue hook), i can see useEffect() function is called.

now, in this following line, I am surprised that inputValue will have the old value and my understanding was useEffect (with inputValue as dependency) will run once that is updated.

useEffect(() => {
previousInputValue.current = inputValue; 
}, [inputValue]);

Could someone please guide me on why inputValue won't have the latest/newest updated value inside useEffect()?

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ reactjs โ€บ difference-between-usestate-and-useeffect-hook-in-reactjs
Difference Between useState and useEffect Hook in ReactJS - GeeksforGeeks
July 23, 2025 - Both useState and useEffect are ... in React. useState lets you manage and update the component state while useEffect allows you to handle side effects like the data fetching, DOM manipulation and cleanup....
Top answer
1 of 3
83

To put it simply, both useState and useEffect enhance functional components to make them do things that classes can but functional components (without hooks) cannot:

  • useState allows functional components to have state, like this.state in class components.
  • useEffect allows functional components to have lifecycle methods (such as componentDidMount, componentDidUpdate and componentWillUnmount) in one single API.

Refer to the examples below for further illustration:

useState

class CounterClass extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 1 };
  }
  
  render() {
    return <div>
      <p>Count: {this.state.count}</p>
      <button onClick={() => this.setState({ 
        count: this.state.count + 1
      })}>Increase</button>
    </div>;
  }
}

function CounterFunction() {
  const [count, setCount] = React.useState(1);
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => 
        setCount(count + 1)}
      >Increase</button>
    </div>
  );
}

ReactDOM.render(
  <div>
    <CounterClass />
    <CounterFunction />
  </div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

useEffect

class LifecycleClass extends React.Component {
  componentDidMount() {
    console.log('Mounted');
  }
  
  componentWillUnmount() {
    console.log('Will unmount');
  }
  
  render() {
    return <div>Lifecycle Class</div>;
  }
}

function LifecycleFunction() {
  React.useEffect(() => {
    console.log('Mounted');
    return () => {
      console.log('Will unmount');
    };
  }, []); // Empty array means to only run once on mount.
  return (
    <div>Lifecycle Function</div>
  );
}

ReactDOM.render(
  <div>
    <LifecycleClass />
    <LifecycleFunction />
  </div>
, document.querySelector('#app'));
<script src="https://unpkg.com/[email protected]/umd/react.development.js"></script>
<script src="https://unpkg.com/[email protected]/umd/react-dom.development.js"></script>

<div id="app"></div>

Read more about useState and useEffect on the official React docs.

2 of 3
29

For useState()

First, we have the functional component which did not supported state, in other words, a functional component is a stateless component.

Now, with Hooks, we have the functional component but stateful. It is achieved by using useState.


For useEffect()

First, with stateless functional component, we didn't have component lifecycle hooks. In other words, whenever you want to use component lifecycle hooks, you should consider using class component.

Now, we are able to use component lifecycle hooks without using class component. It is achieved by using useEffect. In other words, now whenever we want to use component lifecycle hooks, we already have two options either using class component or using Hooks with useEffect.


UPDATE

whatโ€™s the exact difference between useState and useEffect?

In simple words, useState allows our functional components which used to be stateless become stateful. And useEffect allows our functional components leverage the component lifecycle hooks which were, in the past, only supported for class components.

Find elsewhere
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ hard time understanding hooks besides usestate and useeffectโ€ฆ.
r/reactjs on Reddit: Hard time understanding hooks besides useState and useEffectโ€ฆ.
June 25, 2023 -

Every time I make a project I use useState and useEffect and never touch any of the other hooks. Because of this I have no clue what they do or why theyโ€™d be useful.

Am I not using them because my projects are too simple or because I simply donโ€™t know how to apply them?

Iโ€™ve been trying to understand them, hooks such as useRef and useReducer and Iโ€™m just having a hard time understanding them.

Is this normal when learning React?

๐ŸŒ
Medium
medium.com โ€บ @manojitdas180306 โ€บ understanding-the-differences-between-usestate-and-useeffect-in-react-5296ce78d574
Understanding the Differences Between useState and useEffect in React | by Manojit Das | Medium
July 9, 2024 - The return statement inside useEffect is a cleanup function that clears the timer when the component unmounts or when dependencies change. State vs. Side Effects: useState: Manages local state within a component.
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ necessary to use hooks outside of usestate and useeffect?
r/reactjs on Reddit: Necessary to use hooks outside of useState and useEffect?
May 25, 2023 -

Hi - noobie react dev here. Yet to land my first job but have spent a good amount of time using

So I have built out many projects in react (simple ones) and for all of the projects, I was able to achieve the desired effects using only these two hooks.

Is this a problem? Was wondering how many of you front-end developers actually use all or most of the hooks on a consistent basis? Do you guys recommend that I learn and get comfortable with the other hooks before applying to jobs?

Thanks in advance :D

๐ŸŒ
SheCodes
shecodes.io โ€บ athena โ€บ 125174-difference-between-usestate-and-useeffect-in-react
[React] - Difference between useState and useEffect in | SheCodes
Learn about the difference between useState and useEffect hooks in React, and how they are used for state management and side effects.
๐ŸŒ
Reddit
reddit.com โ€บ r/webdev โ€บ a reminder that there are more react hooks than usestate and useeffect!
r/webdev on Reddit: A reminder that there are more react hooks than useState and useEffect!
October 30, 2025 -

Please don't roast me for wanting to share this, but I've been learning more about newer react hooks and remembered when I knew no other hooks than useState and useEffect lol. I am not here to judge, I am here to help spread the knowledge with a few hooks I have became way more familiar and comfortable with! Here is a reminder for all the hooks you don't use but probably should!

useMemo: The "I already did it" hook

useMemo helps prevent unnecessary re-computation of values between renders.
Itโ€™s perfect for expensive functions or large array operations that depend on stable inputs.

const filteredData = useMemo(() => {
      return thousandsOfDataPoints.filter((item) => item.isImportant && item.isMassive);
}, [thousandsOfDataPoints]);

Without useMemo, React would re-run this filtering logic every render, even when thousandsOfDataPoints hasnโ€™t changed.
With it, React only recalculates when thousandsOfDataPoints changes โ€” saving you cycles and keeping components snappy. The takes away, use useMemo for large datasets that don't really change often. Think retrieving a list of data for processing.

useCallback: The "Don't do it unless I tell you" to hook

useCallback prevents unnecessary re-renders caused by unstable function references.
This becomes essential when passing callbacks down to memorized child components.

    import React, { useState, useCallback, memo } from "react";
    
    const TodoItem = memo(({ todo, onToggle }) => {
      console.log("Rendered:", todo.text);
      return (
        <li>
          <label>
            <input
              type="checkbox"
              checked={todo.completed}
              onChange={() => onToggle(todo.id)}
            />
            {todo.text}
          </label>
        </li>
      );
    });
    
    export default function TodoList() {
      const [todos, setTodos] = useState([
        { id: 1, text: "Write blog post", completed: false },
        { id: 2, text: "Refactor components", completed: false },
      ]);
    
      // useCallback keeps 'onToggle' stable between renders
      const handleToggle = useCallback((id: number) => {
        setTodos((prev) =>
          prev.map((t) =>
            t.id === id ? { ...t, completed: !t.completed } : t
          )
        );
      }, []);
    
      return (
        <ul>
          {todos.map((todo) => (
            <TodoItem key={todo.id} todo={todo} onToggle={handleToggle} />
          ))}
        </ul>
      );
    }

Every render without useCallback creates a new function reference, triggering unnecessary updates in children wrapped with React.memo.
By stabilizing the reference, you keep your component tree efficient and predictable.

Why This Is Better

  • Without useCallback, handleToggle is recreated on every render.

  • That means every TodoItem (even unchanged ones) would re-render unnecessarily, because their onToggle prop changed identity.

  • With useCallback, the function reference is stable, and React.memo can correctly skip re-renders.

In large lists or UIs with lots of child components, this has a huge performance impact.

The take away, useCallback in child components. Noticeable when their parents are React.memo components. This could 10x UIs that rely on heavy nesting.

useRef: The "Don't touch my SH!T" hook

useRef isnโ€™t just for grabbing DOM elements, though admittedly that is how I use it 9/10 times. It can store mutable values that persist across renders without causing re-renders. Read that again, because you probably don't get how awesome that is.

    const renderCount = useRef(0);
    renderCount.current++;

This is useful for things like:

  • Tracking render counts (for debugging)

  • Storing timers or subscriptions

  • Holding previous state values

    const prevValue = useRef(value);
    useEffect(() => {
      prevValue.current = value;
    }, [value]);

Now prevValue.current always holds the previous value, a pattern often overlooked but extremely handy.

useDeferredValue: The "I'm on my way" hook

For modern, data-heavy apps, useDeferredValue (React 18+) allows you to keep UI snappy while deferring heavy updates.

const deferredQuery = useDeferredValue(searchQuery);
    const filtered = useMemo(() => filterLargeList(deferredQuery), [deferredQuery]);

React will render the UI instantly, while deferring non-urgent updates until the main thread is free, a subtle UX upgrade that users definitely feel.

useTransition: The "I'll tell you when I am ready" hook

useTransition helps you mark state updates as non-urgent.
Itโ€™s a game-changer for transitions like filters, sorting, or route changes that take noticeable time.

    const [isPending, startTransition] = useTransition();
    
    function handleSortChange(sortType) {
      startTransition(() => {
        setSort(sortType);
      });
    }

This keeps the UI responsive by allowing React to render updates gradually, showing loading indicators only when needed.

Bonus: useImperativeHandle for Library Builders like me!

If you build reusable components or libraries, useImperativeHandle lets you expose custom methods to parent components through refs.

    import React, {
      forwardRef,
      useRef,
      useImperativeHandle,
      useState,
    } from "react";
    
    const Form = forwardRef((props, ref) => {
      const [name, setName] = useState("");
      const [email, setEmail] = useState("");
    
      // Expose methods to the parent via ref
      useImperativeHandle(ref, () => ({
        reset: () => {
          setName("");
          setEmail("");
        },
        getValues: () => ({ name, email }),
        validate: () => name !== "" && email.includes("@"),
      }));
    
      return (
        <form className="flex flex-col gap-2">
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Name"
          />
          <input
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="Email"
          />
        </form>
      );
    });
    
    export default function ParentComponent() {
      const formRef = useRef();
    
      const handleSubmit = () => {
        if (formRef.current.validate()) {
          console.log("Form values:", formRef.current.getValues());
          alert("Submitted!");
          formRef.current.reset();
        } else {
          alert("Please enter a valid name and email.");
        }
      };
    
      return (
        <div>
          <Form ref={formRef} />
          <button onClick={handleSubmit} className="mt-4 bg-blue-500 text-white px-4 py-2 rounded">
            Submit
          </button>
        </div>
      );
    }

This allows clean control over internal component behavior while keeping a tidy API surface.

Hope you enjoyed the read! I am trying to be more helpful to the community and post more educational things, lessons learned, etc. Let me know if you think this is helpful to this sub! :)

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ usestate vs useref
r/reactjs on Reddit: useState vs useRef
February 3, 2025 - When you have a timer that changes frequently (like every second), you need to store its reference. If you use useState to store the timer, it will trigger a re-render every time the timer updatesโ€”which can be inefficient if the timer updates ...
๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ is it okay to use many usestate and useeffect?
r/reactjs on Reddit: Is it okay to use many useState and useEffect?
July 4, 2022 -

Hello

I feel I'm not doing the right thing by using many/a lot useState and useEffect,
I'm using about 15 useState and about 5 useEffect xD
So in general is it okay to use as many as I do, or what I'm doing is totally wrong?

Thanks

Edit:
Sorry for my late reply, internet was down in my area after I posted.
Anyway, so I refactored the component, now it contains one useReducer and one useState and three useEffect, I also moved a small part into its own component.

Thanks to you guys, I feel the component logic is much better now,
although I'm sure it's not that good lol, but at least it's better.

BTW Some of you said combine multiple states into one bigger state using object in useState,
but I'm pretty sure that I saw somewhere (I think in react docs?) that it's better to actually split a big state into smaller states using multiple useState.

๐ŸŒ
Reddit
reddit.com โ€บ r/reactjs โ€บ [noob] are useeffect hooks really that bad??
r/reactjs on Reddit: [Noob] are useEffect hooks really that bad??
February 10, 2025 -

am a junior full stack dev and my experience with react are limited to school projects. i've always use useEffect hooks and everything is great until i heard my senior devs complaining about the team using too many useEffect hooks in our codebase. things like our components get rendered unnecessarily and slowing down performance. ever since then, i'm very conscious about using useEffect.

so question is, are useEffect hooks really that bad and should i avoid using them at all cost? love to hear from yall cuz this is bothering me a lot and i want to be a better engineer

๐ŸŒ
Reddit
reddit.com โ€บ r/learnjavascript โ€บ replicate react usestate and useeffect in vanilla js?
r/learnjavascript on Reddit: Replicate React useState and useEffect in vanilla JS?
April 6, 2024 -

Long story short, I'm trying to work on a custom little JS framework for fun. I was hoping to implement something akin to React's useState and useEffect using vanilla JS so that I can essentially do this:

<script>
     const [firstName, setFirstName] = useState('Bill');
     const [lastName, setLastName] = useState('Gates');

     useEffect(() => { 
        console.log(firstName);
     }, [firstName]);

     useEffect(() => { 
        console.log(firstName, lastName);
     }, [firstName, lastName]);
</script>

But this seems to be really hard to implement without React's rerendering functionality. I don't want to deal with renders I just want to essentially watch for state changes so I can trigger side effects. I tried utilizing Proxies to listen for state changes but honestly it got out of control quickly. I'm now considering rewriting it to rely on event triggers on setState and listeners to trigger effects. But I figured I'd ask here first how might i go about building something like this.

Top answer
1 of 5
10
The thing is the way React hooks are implemented is intrinsically tied to the render cycle. If your example code were in a React component, it would happen like this: Something calls setFirstName This updates the internal state value and triggers a render The render triggers the function which your React component is made out of to run again The function calls useState which returns the updated value of firstName The function calls useEffect which compares the values in the dependency array to the old values, sees they have changed, and runs the callback So without setFirstName triggering a render, useState doesn't get called again to return the updated value, and useEffect doesn't get called again to check the dependency array. We can write something kind of like useEffect easily enough with a closure in a module. let previousDependencies = []; export const useEffectish = (callback, dependencies) => { let isDependenciesChanged = false; for (let i = 0; i < dependencies.length; i += 1) { if (dependencies[i] !== previousDependencies[i]) { isDependenciesChanged = true; } } previousDependencies = dependencies; if (isDependenciesChanged) { callback(); } }; However, without the render cycle we'll need to manually call this again to check for changed dependencies. We also can't use it multiple times since we are only tracking one set of old dependencies. React solves this by... tracking what order you call useEffect in each render. This is why you have to always call hooks in the same order and the same number of times. Really what I think you want is something far simpler: a listener pattern. You just need a way to register a listener, and then a way to trigger any listeners. Let's use closers again, but this time we'll enclose the variables in a function instead of a module. const createLiveValue = (initialValue) => { let value = initialValue; let listeners = []; const getValue = () => value; const setValue = (nextValue) => { value = nextValue; for (const listener of listeners) { listener(value); } }; const addListener = (listener) => { listeners.push(listener); }; const removeListener = (listener) => { listeners = listeners.filter(fn => fn !== listener); }; return [ getValue, setValue, addListener, removeListener ]; }; Then we would use it like this: const [getName, setName, onName] = createLiveValue('Bill'); onName(console.log); setName('Steve'); // Steve logs to the console
2 of 5
1
use state ? - input hidden , use effect - window.onload ? component ? web component ? hooks ? not sure . jsx ? you need to create own parser and and create document.create element and render back to inner html , back button and refresh ? history.push state i think . event delegate css class for interaction with button event .