简体   繁体   中英

React custom hooks state change but useeffect not rerendering

I build custom hook for updating filter state that is shared between two component.

Even when adding the filter as dependency on the useEffect the other component does not accept the state change. Why is that happening?

later edit: I'm building a library where I want my users use the library's components without define special care of moving props to the correct component. I want it to work out of the box with out the need to define that.

Here is my code:

The custom hook:

export default function SharedFilter() {
    const [filter, setFilter] = useState({filter: "Last 24 hours"});

    function setTheFilter(newFilter){
        setFilter({filter: newFilter.filter});
    }

    return [filter, setTheFilter];
}

The component that change the filter:

export default function TimeFilter() {

    const [filter, setFilter] = SharedFilter();

    return(
        <div>
            <select id="timeFilter" onChange={(event) => {
                setFilter({filter : event.target.value})
            }}>
                <option value="Last 24 hours">Last 24 hours</option>
                <option value="Last 48 hours">Last 48 hours</option>
                <option value="Last week">Last week</option>
                <option value="Last Month">Last Month</option>
                <option value="Last Year">Last Year</option>
            </select>
        </div>
    );
}

This is the component that the useEffect is not working:

export default function Chart() {

    const [filter, setFilter] = SharedFilter();

    useEffect(() => {
    }, [filter.filter]);

    return (
        <div>
            {filter.filter}
        </div>
    );
}

Hooks are not an angular services - they don't share a state. You can't use setFilter in one component and use filter hoping to get the same value in another. For that you should use context or pass it in props.

BTW, you should prefix your custom hooks with use, so useSharedFilter

如果是 globla 数据,则通过useContext使用上下文,因此您无需自定义新挂钩。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM