in

Simple useGlobalState hook for React


Codesandbox example

Example:

import { useGlobalState } from 'use-global-state-react';

const TASK_STORE_KEY = 'tasks';

const Tasks = () => {
    const [tasks, setTasks] = useGlobalState<string[]>(TASK_STORE_KEY, []);
    
    ...
}

and then you can use the same hook everywhere, data will be shared across components and component will rerender if changes happened in store:

const AddTaskButton = () => {
    const [, setTasks] = useGlobalState(TASK_STORE_KEY, []);
    
    const onTaskAdd = (newTask: stirng) => setTasks(prev => [...prev, newTask]);
    
    ...
}

const TasksTotal = () => {
    const [tasks] = useGlobalState<string[]>(TASK_STORE_KEY, []);
    
    return tasks.length;
}

or use helper createGlobalStore to create custom hook with shared data:

import { createGlobalStore } from 'use-global-state-react';

const useTasks = createGlobalStore<string[]>(TASK_STORE_KEY, []);


const Tasks = () => {
    const [tasks, setTasks] = useTasks();
    ...
}

View Github


Rodgers breaks Favre’s career TD mark as Packers hold off Browns fightback thumbnail

Rodgers breaks Favre’s career TD mark as Packers hold off Browns fightback

Getting my gitlab commit history into github