Answer the question
In order to leave comments, you need to log in
How to properly use the useEffect hook?
Good day. Often you have to write hooks like this
useEffect(() => {
dispatch(
someAction({ ...params, anotherParams, page}),
)
}, []);
Answer the question
In order to leave comments, you need to log in
First, useEffect will always fire when the component is rendered. Update the request or state and be sure useEffect will be called. This means that you need to enter an internal state for the component, indicating that it is rendered.
const Comp = () => {
const [ready, setReady] = useState(false);
const dispatch = useDispatch();
useEffect(() => {
if (ready === false) { // после отображения элемента будет вызвана функция, `ready` все еще будет `false`, поэтому выполнив свой код, надо вручную задать ей true, чтоб код не вызывался дважды.
dispatch({ type: 'increment-counter' });
setReady(true);
}
});
};
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question