obtainable fly bells wise terrific lunchroom light upbeat rhythm wild
This post was mass deleted and anonymized with Redact
React: useEffect vs useMemo vs useState - javascript
Aren't useEffect and useState redundant?
Thoughts on avoiding useEffect/useState when possible in React?
Can someone please explain the difference between useState and useReducer hook like I'm 5?
Videos
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.
Your points are basically correct, some minor clarification:
useState is causing a re-render on the call of the setState method (second element in the array returned). It does not have any dependencies like useMemo or useEffect.
useMemo only recalculates a value if the elements in its dependency array change (if there are no dependencies - i.e. the array is empty, it will recalculate only once). If the array is left out, it will recalculate on every render. Calling the function does not cause a re-render. Also it runs during the render of the component and not before.
useEffect is called after each render, if elements in its dependency array have changed or the array is left out. If the array is empty, it will only be run once on the initial mount (and unmount if you return a cleanup function).
You can always check Hooks API Reference, which is a pretty solid documentation in my opinion
- The return value of
useEffect(callback, [dependency])isvoidand It executes afterrender(). - The return value of
useMemo(callback, [dependency])is NOTvoidbut memoized value and It executes DURINGrender().
useEffect() can give same optimization as of useMemo() under the following circumstances:
- The state variable used in the expensive computation (i.e., count1) is the only dependency of the useEffect.
- When we don't mind storing the expensively computed value in state variable.
const [count1, setCount1] = useState(0);
const [expensiveValue, setExpensiveValue] = useState(null);
useEffect(() => {
console.log("I am performing expensive computation");
setExpensiveValue(((count1 * 1000) % 12.4) * 51000 - 4000);
}, [count1]);
- Only difference is,
useEffect()makes the expensively computed value available afterrender()whileuseMemo()makes the value available during therender(). - Most of the time it does not matter because if that value has been calculated for rendering in the UI,
useEffect()anduseMemo()both will make the value available before browser finishes painting.