1

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>
    );
}
Eden G
  • 60
  • 8

2 Answers2

3

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

Vlad Gincher
  • 1,052
  • 11
  • 20
  • Thank you for the answer. What do you mean pass it in props? – Eden G Feb 06 '20 at 20:43
  • You can use a parent component that will hold the state, and pass setFilter to `TimeFilter` and filter to `Chart`. for example, ``. To get it `function SharedFilter({setFilter}) {`. – Vlad Gincher Feb 06 '20 at 20:47
  • I'm building a library. I don't want the users to need to define that props. I need it to work out of the box without the user need to define that props. Is there any way doing that? – Eden G Feb 07 '20 at 04:52
0

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

mohamed ibrahim
  • 567
  • 4
  • 12