obtainable fly bells wise terrific lunchroom light upbeat rhythm wild
This post was mass deleted and anonymized with Redact
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 ๐
Videos
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?
I have read many documentation and watched several videos but didn't able to understand the clear differences ):
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()?
Current Value: {inputValue}
Previous Value: {previousInputValue.current}
); }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:
useStateallows functional components to have state, likethis.statein class components.useEffectallows functional components to have lifecycle methods (such ascomponentDidMount,componentDidUpdateandcomponentWillUnmount) 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.
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
useStateanduseEffect?
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.
I saw a guy get reemed in some code he shared because he was using useState in a useEffect.
I have some areas of my code where I do this.
For example I will use tanstack to fetch data. Iโll tie a useEffect to that data and setState so that data can be edited in a form.
How else would you do this?
**** Edit. I meant setState in useEffect.
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?
I've been learning React for a few months now and I feel like I've only been learning the basics of useState with every new tutorial/interactive tutorial/guide other than the basics of react which is just basic functional components and props.
Is React only usestate? Why is there such a big emphasis on this?
My understanding is that useState allows a component to rerender when one specific state changs. However, useEffect allows us to do exactly this plus more (since we have a whole array instead of just one variable). What am I missing here?
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
Title says it all.
I've been a professional react dev for over a year now and I almost never use any hook other than useEffect and useState. To be fair, I am usually able to get everything I need done with those... but I know I can do better. Any tips for how to practice using other hooks? Good ones to start with? I've learned them before but I usually forget them and then I never remember to use them when I probably should.
Thank you.
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! :)
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.
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
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.