Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
838 views
in Technique[技术] by (71.8m points)

reactjs - Accessing context from useEffect

I have a context that is used to show a full page spinner while my application is performing long running tasks.

When I attempt to access it inside useEffect I get a the react-hooks/exhaustive-deps ESLint message. For example the following code, although it works as expected, states that busyIndicator is a missing dependency:

const busyIndicator = useContext(GlobalBusyIndicatorContext);

useEffect(() => {
    busyIndicator.show('Please wait...');
}, []);

This article suggests that I could wrap the function with useCallback which might look as follows:

const busyIndicator = useContext(GlobalBusyIndicatorContext);
const showBusyIndicator = useCallback(() => busyIndicator.show('Please wait...'), []);

useEffect(() => {
    showBusyIndicator();
}, [showBusyIndicator]);

Although this works it has moved the issue to the useCallback line which now complains about the missing dependency.

Is it ok to ignore the ESLint message in this scenario or am I missing the something?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If your busyIndicator is not changed during the life of the component, you could simply add it as a dependency to useEffect:

const busyIndicator = useContext(GlobalBusyIndicatorContext);

useEffect(() => {
    busyIndicator.show('Please wait...');
}, [busyIndicator]);

If busyIndicator could be changed and you don't want to see an error, then you could use useRef hook:

const busyIndicator = useRef(useContext(GlobalBusyIndicatorContext));

useEffect(() => {
    busyIndicator.current.show('Please wait...');
}, []);

The useRef() Hook isn’t just for DOM refs. The “ref” object is a generic container whose current property is mutable and can hold any value, similar to an instance property on a class. read more


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...