0
votes

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>
    );
}
2

2 Answers

2
votes

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

0
votes

If it is a globla data use context instead through useContext so you don't need to custom a new hook.