Create an example page
import * as React from "react";
import { graphql } from "gatsby";
export default function Page()
{
return (
<div>
This is a super bland page
</div>
);
}
Create the layout
import React from "react";
export default function Layout({ children })
{
return (
<div>
This is the layout component
<div>
{ children }
</div>
</div>
);
}
Use it
return (
<Layout>
<div>
This is a super bland page
</div>
</Layout>
);
Test it:
Create a component that renders it's state
Create a button
Create a react hook
Make the button toggle the state
Test:
Note: The toggle state doesn't persist on page refresh
Create a custom react hook function
Make it persist on page refresh
localStorage.getItem("toggleState");
JSON.parse(the returned value)
Check if it's null
on toggle, call localStorage.setItem("toggleState", state)
Isolate that code, into the custom hook
Use it on another page:
Finished example of the above:
import { useState } from "react";
export default function useToggle()
{
const storedState = JSON.parse(localStorage.getItem("toggleState"));
const initialState = storedState == null ? 'true' : storedState;
const [state, setState] = useState(initialState);
const toggleStateFunction = function()
{
const newState = !state;
setState(newState);
localStorage.setItem("toggleState", newState);
}
return [state, toggleStateFunction];
}