I set the variable to the value in a parent function, then pass it as context to children, and then I set the UseEffect to alert it every time the variable changes, but it only alerts once when my App is restarted. I have 2 components to which I pass the same context, and one of them works fine, and another doesn’t.
Here is my Context and variables:
interface WidgetContextType {
accept: boolean;
sortType: string;
}
const AcceptContext = React.createContext<WidgetContextType>({ accept: false, sortType: '' });
const [showTodo, setShowTodo] = useState(false);
const [sortType, setSortType] = useState('');
<Modal show={showSort} onHide={() => setShowSort(false)}>
<Modal.Header closeButton>
<Modal.Title>Sort Applications</Modal.Title>
</Modal.Header>
<Modal.Body>How would you like to sort your Applications?</Modal.Body>
<Modal.Footer>
<Button variant="secondary" onClick={handleCloseNoSort}>No sorting</Button>
<Button variant="primary" onClick={handleCloseNameSort}>By name</Button>
</Modal.Footer>
</Modal>
In the end I wrap children into Contgext:
<AcceptContext.Provider value={{ accept: accept, sortType: sortType }}>{children}</AcceptContext.Provider>
And here is the end of my file:
export const useAcceptContext = (): WidgetContextType => {
return useContext(AcceptContext);
};
When I call it in my Todo file – it works fine, and when in Favorite application file – it doesn’t.
Here is how I call it:
const s = useAcceptContext();
const sortType = s.sortType;
// Use useEffect to re-render FavoriteApps whenever sortType changes
useEffect(() => {
alert(`sortType changed: ${sortType}`);
}, [sortType]);
const sortedApps = useMemo(() => {
// Sort logic based on sortType
return [...apps].sort((a, b) => {
if (sortType === 'name') {
return a.name.localeCompare(b.name); // Sort alphabetically by name
}
return 0; // Default: no sorting
});
}, [apps, sortType]);
4