Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React can I create 'setState' function in custom hook?

I successfully applied local storage in my component and would like to create my first hook, which will take care of the local storage, so I can re-use it in my other components.

/*   EXAMPLE   */
//useState:
const [state,setState] = useState("");
setValue("Hello"); // WORKS!

//useLocalHook:
const [hook_value,setHookValue] = useLocalStorage("");
setHookValue("New Value"); // NOT WORKING

I read guides about custom hooks, but they are not using the setFunction for their custom hooks, is this impossible to do?

Parent:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

   // Local storage
    const [data,setData] = useLocalStorage("mydata","");
    useEffect(()=>{
        setData(new_value);
    },[data]);

Hook:

const useLocalStorage = (storage_key,initial_value) => {

    const [value,setValue] = useState(getLocalStorage(storage_key,initial_value));

    /*          LOCAL STORAGE           */
    function saveLocalStorage(key,value){
        if (typeof window !== "undefined") {
            // Set New Default Value
            const saved_value = JSON.stringify(value);
            console.log(`Key:${key} stored:${value}`);
            localStorage.setItem(key,saved_value);
        }
    }
    function getLocalStorage(key,initial_value)
    {
        if (typeof window !== "undefined") {
            const value = JSON.parse(localStorage.getItem(key));
            console.log(`Key:${key} received:${value}`);
            if(value)
            {
                return value;
            }
        }
        // Not found, return initial value
        return initial_value;
    }
    function clearLocalStorage()
    {
        localStorage.clear();
    }
    function setValue(new_val)
    {
        value = new_val;
    }
    // Save settings in local storage
    useEffect(()=>{
        saveLocalStorage(storage_key,value);
    },[value]);

    // Return value
    return [value];
}

What am I not understanding /& doing wrong if it’s possible to change the value with custom hooks?

>Solution :

You need to return setValuefn in your custom hook, so you can use used it inside useEffect

Hook:

    const useLocalStorage = (storageKey,initialValue) => {
       const [value,setValue] = useState(getLocalStorage(storageKey,initialValue));

    return [value, setValue]

And now in the parent you can use setData

Parent

   const [data,setData] = useLocalStorage("mydata","");
     useEffect(()=>{
        setData(new_value);
     },[data]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading