What is the best practice to replace the usage of setState
function from React.Component --
https://reactjs.org/docs/react-component.html#setstate
setState(updater, [callback])
where updater has the signature
(state, props) => stateChange
(So the new state depends on previous state and also props)
-- using React hooks?
When I searched for the useState
hook's API, https://reactjs.org/docs/hooks-reference.html#functional-updates
Functional updates If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value. Here’s an example of a counter component that uses both forms of setState:
function Counter({initialCount}) {
const [count, setCount] = useState(initialCount);
return (
<>
Count: {count}
<button onClick={() => setCount(initialCount)}>Reset</button>
<button onClick={() => setCount(prevCount => prevCount - 1)}>-</button>
<button onClick={() => setCount(prevCount => prevCount + 1)}>+</button>
</>
);
}
the function updating the state, setCount
, does not take props as an argument.
Is the best practice for this to use useEffect
hook, with props as a dependency?
Could anyone explain why this was separated in the React hooks?